Skip to content

Instantly share code, notes, and snippets.

@ranedk
Created August 6, 2020 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ranedk/7d43de58777544d697150575665d51a0 to your computer and use it in GitHub Desktop.
Save ranedk/7d43de58777544d697150575665d51a0 to your computer and use it in GitHub Desktop.
Jedis pool implementation in Kotlin
package com.pibpl.cache
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.KotlinModule
import com.pibpl.settings.ConfigManager
import org.springframework.stereotype.Service
import redis.clients.jedis.Jedis
import redis.clients.jedis.JedisPool
import redis.clients.jedis.JedisPoolConfig
import redis.clients.jedis.Pipeline
@Service
object CacheManager {
// TODO: GROT and use Spring boot's method
private lateinit var jedisPool: JedisPool
init {
jedisPool = JedisPool(
JedisPoolConfig(),
ConfigManager.redisHostname,
ConfigManager.redisPort,
10000,
ConfigManager.redisPassword,
ConfigManager.redisDatabase
)
}
fun destroy() {
jedisPool.destroy()
}
fun getJedis(): Jedis {
return jedisPool.resource
}
fun getPipeline(): Pipeline {
return jedisPool.resource.pipelined()
}
fun <T> get(key: String, clazz: Class<T>): T {
val value: String = getJedis().get(key)
val mapper = ObjectMapper().registerModule(KotlinModule())
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
// Temp addition, rectify later.
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
return mapper.readValue(value, clazz)
}
fun set(key: String, value: Any): Unit {
val mapper = ObjectMapper().writeValueAsString(value)
getJedis().set(key, mapper)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment