Spring Data Redis - @Transactional support on Repository

4k views Asked by At

We're using spring-boot-starter-parent 1.4.1 together with spring-boot-starter-redis and spring-boot-starter-data-redis. We use redis for (a) message passing to an external app and (b) to store some information in a repository. Our redis config looks like this

@Configuration
@EnableRedisRepositories
open class RedisConfig {

    @Bean // for message passing
    @Profile("test")
    open fun testRedisChannelProvider(): RedisParserChannelProvider {
        return RedisParserChannelProvider("test_parser:parse.job", "test_parser:parse.joblist")
    }

    @Bean // for message passing
    @Profile("!test")
    open fun productionRedisChannelProvider(): RedisParserChannelProvider {
        return RedisParserChannelProvider("parser:parse.job", "parser:parse.joblist")
    }

    @Bean // for message passing
    open fun parseJobTemplate(connectionFactory: RedisConnectionFactory): RedisTemplate<String, ParseJob> {
        val template = RedisTemplate<String, ParseJob>()
        template.connectionFactory = connectionFactory
        template.valueSerializer = Jackson2JsonRedisSerializer<ParseJob>(ParseJob::class.java)

        return template
    }

    //@Bean // for message passing
    //open fun parseJobListTemplate ...

    // no template for repository

With this config the message passing is working nicely as well as writing to/reading from the repository. Now I am trying to get @Transactional working for communication with the repository, but I have not succeeded so far. I already followed the example config in the docs and manually enabled transaction support on it:

@Bean
open fun redisTemplate(): RedisTemplate<*, *> {

    val template = RedisTemplate<ByteArray, ByteArray>()
    template.setEnableTransactionSupport(true)
    return template
}

...but this is apparently not the way to go. Currently, everything written to the repository (in particular during tests) stays there.

1

There are 1 answers

1
mp911de On BEST ANSWER

@Transactional use of Redis repositories is not possible, and I doubt it will work at all.

The reason behind is how Spring Data Redis repository support works: RedisKeyValueAdapter relies on results of write and read operations that are issued while persisting an object.

Redis transactions behave more like deferred batches, so it's not possible to wrap Redis repository support inside a transaction but require a different approach and impose several limitations.