Hey question: I'm having trouble coding up a sprin...
# announcements
b
Hey question: I'm having trouble coding up a spring-data-redis transaction, wondering if anyone can help me out I'm working from an example in Java but the normal ways of converting to Kotlin aren't working: https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#tx Specifically, here's the java code example:
To simplify things I split out the callback to try to code it up. Kotlin seems to be struggling with the generics. I got this to compile (finally, after spending about half a day on it), but it is really ugly val callback = object : SessionCallback<List<Any>> { override fun <K: Any, V: Any> execute(operations: RedisOperations<K, V>?): List<Any> { operations!!.multi() operations.opsForValue().set(record.userId as K, record as V) return operations.exec() } }
Also here's the interface for SessionCallback: public interface SessionCallback<T> { <K, V> T execute(RedisOperations<K, V> var1) throws DataAccessException; }
Note all the replies on this are from me adding clarifying details
p
I had a similar issue with the redis API and resolved it with an extension function on the
RedisOperations<K, V>
interface. This should show you the approach:
Copy code
@Component
class MyRedisComponent(private val redisTemplate: StringRedisTemplate) {
    fun addStuffWithExt() {
        val txResults = redisTemplate.executeSession { operations ->
            operations.multi()
            operations.opsForSet().add("key", "value1")
            operations.exec()
        }
    }
}

fun <K : Any, V : Any, T : Any?> RedisOperations<K, V>.executeSession(session: (RedisOperations<K, V>) -> T): T? =
    execute(object : SessionCallback<T> {
        @Suppress("UNCHECKED_CAST")
        override fun <K2 : Any?, V2 : Any?> execute(operations: RedisOperations<K2, V2>): T =
            session(operations as RedisOperations<K, V>)
    })
b
Thanks