1

I've been triyng to use the Jackson2JsonRedisSerializer to serialize a custom instance as the hash value in a Redis store. It seems that even though I have correctly created the template, no hash is created.

Just a note that I'm using spring-data-reactive-redis with spring-webflux with Kotlin.


data class Movie(
    @get:JsonProperty("Id")
    val id: String?,
    @get:JsonProperty("Title")
    val title: String,
)

@Configuration
class RedisConfig {
    @Bean
    fun hashTemplate(factory: ReactiveRedisConnectionFactory): ReactiveRedisTemplate<String, Movie> {
        val serializationContext = RedisSerializationContext.newSerializationContext<String, Movie>(StringRedisSerializer())
            .hashKey(StringRedisSerializer())
            .hashValue(Jackson2JsonRedisSerializer(Movie::class.java))
            .build()

        return ReactiveRedisTemplate(factory, context)
    }
}

Here is an example of adding data using this template.


@Component
class DataLoader(@Qualifier("hashTemplate") private val template:  ReactiveRedisTemplate<String, Movie>) {

    @PostConstruct
    fun loadData() {
        Flux.fromIterable(
            listOf(Movie("1", "Avengers: Endgame"), Movie("2", "Black Widow"))
        )
        .flatMap { movie ->
            template.opsForHash<String, Movie>().put("Movies", movie.id, movie)
        }
        .thenMany(template.opsForHash<String, Movie>().entries("Movies"))
        .subscribe { m -> println(m) }
    }

}

Can anyone help me with why Spring is not using the template I have created.

  • What are you seeing after you start your app? Are you seeing any errors? I tried your code, though I made `Movie.id` non-nullable, and I see the hash values being created. For e.g., `hget Movies 1` returns `"{\"Id\":\"1\",\"Title\":\"Avengers: Endgame\"}"` – chrsblck Jan 14 '20 at 03:28
  • were you able to resolve this? – jmadan Nov 07 '20 at 07:30
  • "_Spring is not using the template I have created_"? How do you know that? Is there an actual problem described in your question, because if there is, I'm not seeing it. – Abhijit Sarkar Nov 12 '20 at 02:02

1 Answers1

0

Problem can be cause of Jackson cannot work with Kotlin objects. Add jackson-module-kotlin to your dependencies and declare serializer like that

val valueSerializer = Jackson2JsonRedisSerializer(jacksonObjectMapper(),Movie::class.java)


val serializationContext = RedisSerializationContext.newSerializationContext<String, Movie>(StringRedisSerializer())
            .key(StringRedisSerializer())
            .value(valueSerializer)
            .hashKey(StringRedisSerializer())
            .hashValue(valueSerializer)
            .build()