skip to Main Content

I am using ReactiveRedisOperations with the driver of lettuce to write to Redis.

@Autowired
ReactiveRedisOperations<String, Foo> redisOperation;

public Mono<Boolean> save(Foo foo) {
    redisOperation.map(operation -> 
     operation
     .opsForValue()
     .set(foo.getId(), foo);

    return Mono.just(true);
}

The serialization is defined as

    private <T> ReactiveRedisOperations<String, T> buildRedisOperations(ReactiveRedisConnectionFactory factory, Class<T> clazz) {
        RedisSerializationContext.RedisSerializationContextBuilder<String, T> builder = RedisSerializationContext
                .newSerializationContext(new StringRedisSerializer());
        Jackson2JsonRedisSerializer<T> serializer = new Jackson2JsonRedisSerializer<>(clazz);
        RedisSerializationContext<String, T> context = builder.value(serializer).build();
        return new ReactiveRedisTemplate<>(factory, context);
    }

This works however the data type of the Foo object is saved as String. I want to save the Foo object in Redisjson datatype.

How to use reactively write to redis and save in REDISJSON format?

PS: I dont want to use lua script solution for this.

2

Answers


  1. ReactiveRedisOperations are meant for basic redis operations only (https://docs.spring.io/spring-data/redis/docs/current/api/org/springframework/data/redis/core/ReactiveRedisOperations.html).

    If you want to continue using lettuce along with reactive operations, use https://github.com/redis-developer/lettucemod instead.

    This library provides RedisJSON support

    Login or Signup to reply.
  2. Have you tried to initialize a dedicate ReactiveRedisTemplate bean for Foo class?

    @Bean
    public ReactiveRedisTemplate<String, Foo> reactiveRedisTemplate(ReactiveRedisConnectionFactory factory) {
        RedisSerializationContext.RedisSerializationContextBuilder<String, Foo> builder = RedisSerializationContext.newSerializationContext(new StringRedisSerializer());
        Jackson2JsonRedisSerializer<Foo> serializer = new Jackson2JsonRedisSerializer<>(Foo.class);
        RedisSerializationContext<String, Foo> context = builder.value(serializer).build();
        return new ReactiveRedisTemplate<>(factory, context);
    }
    

    And use it to store values in Redis.

    @Autowired
    ReactiveRedisTemplate<String, Foo> reactiveRedisTemplate;
    
    public Mono<Boolean> save(Foo foo) {
        return reactiveRedisTemplate
              .opsForValue()
              .set(foo.getId(), foo);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search