redis-om-spring icon indicating copy to clipboard operation
redis-om-spring copied to clipboard

Determine a possible integration with @Cacheable

Open varapriya opened this issue 1 year ago • 1 comments

I have an application that uses redis as cache in my springboot application where it uses cache annotations(@Cacheable,@CacheEvict,@CachePut) to leverage redis .I don't see a way to leverage redis-om-spring to query by index to the data that was stored through cache annotations .

Could you show a way to integrate springboot cache with redis-om-spring

varapriya avatar Aug 03 '22 16:08 varapriya

@sazzad16 Some thoughts on this, if you decide to tackle it. When you use @Cacheable with an entity like:

public class Item implements Serializable {
    @Id
    String id;

    String description;
}

say, in a service class like:

    private final ItemRepository itemRepository;

    @Cacheable(value = "itemCache")
    public Item getItemForId(String id) {
        return itemRepository.findById(id)
          .orElseThrow(RuntimeException::new);
    }

You typically use a configuration to determine how the cache entries are serialized:

  @Bean
  public RedisCacheConfiguration cacheConfiguration() {
    return RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(60)).disableCachingNullValues()
        .serializeValuesWith(SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
  }

Witht the above configuration, your cache entries end up looking like this:

"SET" "itemCache::abc" "\xac\xed\x00\x05sr\x00\x1ccom.example.cachingdemo.Item-\xf4\x001\xe0\xdf\xe6W\x02\x00\x02L\x00\x0bdescriptiont\x00\x12Ljava/lang/String;L\x00\x02idq\x00~\x00\x01xpt\x00\x03bart\x00\x03abc" "PX" "600000"

E.g., they are simple Redis keys, not Hashes or ReJSON values. Therefore we would need in the project that produces this artifact:

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>

Override the classes that use plain Redis Strings as the caching mechanism to use either JSON or Hashes (the things that are indexable and searchable in Redis) and users would have to mark the entities with @Indexed or @Searchable as they normally do. The difference is that the cache entries would have to have a different Keyspace prefix that has it's own index, apart from the normal Hash or JSON indexes for regular storage.

If the entity is not a Redis entity, say they are using caching for a relational database (likely the more common case) they would have to mark the entity with some new annotation, maybe @RedisCacheable and use @Indexed and @Searchable in the body of those entities so that we can build the index.

bsbodden avatar Aug 30 '22 03:08 bsbodden