I'm using Spring Data Redis with Kotlin but without Spring data repositories because of the shortcoming in DATAREDIS-1250. So, I created my own little repository.
interface CoroutinesRepository<T : Serializable> {
suspend fun save(entity: T): T
suspend fun findByIdOrNull(id: String): T?
suspend fun deleteById(id: String)
}
and its implementation:
abstract class AbstractCoroutinesRepository<T : Serializable>(clazz: Class<T>) : CoroutinesRepository<T> {
private val hash: String = clazz.simpleName
.// convert class name to hyphenated string
private val idField: Field = clazz.declaredFields
.// find field with @Id annotation
@Autowired
private lateinit var redisTemplate: ReactiveRedisTemplate<Any, Any>
@Autowired
private lateinit var persistenceProperties: PersistenceProperties
override suspend fun save(entity: T): T {
val valueOps = redisTemplate
.opsForValue()
valueOps.set("$hash:${idField.get(entity)}", entity, getTtl(persistenceProperties))
.awaitFirst()
return entity
}
// Other methods omitted
}
used as:
@Repository
class ResponseRepositoryImpl : AbstractCoroutinesRepository<Response>(Response::class.java)
This works and the above code can set and get values from Redis. However, when I query from Redis CLI, I see:
127.0.0.1:6379> SCAN 0
1) "0"
2) 1) "\xac\xed\x00\x05t\x00\x0cuuid:test"
2) "\xac\xed\x00\x05t\x00\x10response:test"
What is this weird string prefix? As I said, it doesn't seem to affect the retrieval, but I'm curious.
Spring Data Redis 2.3.5.RELEASE.
This turned out to be due the use of default JdkSerializationRedisSerializer
, and I'm guessing the weirdness is the field meta information (type etc). Other Redis serializers like GenericJackson2JsonRedisSerializer
don't do this, and the data is saved in a human-readable format.