Search code examples
redisspring-dataspring-data-redis

Spring Data Redis global TTL for all entities


I need to set global TTL to each entity I have and it should be configurable in one place. There is an opportunity to do this via @RedisHash annotation:

@RedisHash(value = "persons",timeToLive = 100)
public class Person{
  ...
}

or I can have a field

 public class Person{
      @TimeToLeave
      Long ttl;
 }

but in this case I can't change it in one place and it's not really comfortable to maintain it. I have a property in applicaiton.properties:

app.redis.ttl=100

and it will be awesome to have an opportunity to change it on property level.


Solution

  • You can configure settings by creating a subclass of KeyspaceConfiguration and configuring @EnableRedisRepositories. There's no property-based configuration for global TTL.

    @EnableRedisRepositories(keyspaceConfiguration = MyKeyspaceConfiguration.class)
    public class MyConfig {
    
    }
    
    public class MyKeyspaceConfiguration extends KeyspaceConfiguration {
    
    
        @Override
        public boolean hasSettingsFor(Class<?> type) {
            return true;
        }
    
        @Override
        public KeyspaceSettings getKeyspaceSettings(Class<?> type) {
    
            KeyspaceSettings keyspaceSettings = new KeyspaceSettings(type, "my-keyspace");
            keyspaceSettings.setTimeToLive(3600L);
    
            return keyspaceSettings;
        }
    }
    

    Deriving from KeyspaceConfiguration is intended to provide Iterable<KeyspaceSettings> initialConfiguration() in the first place but since you want to apply that settings to all classes, the in-place creation of KeyspaceSettings makes more sense.

    You also might want to cache the KeyspaceSettings to not create instances all over so Java 8's Map.computeIfAbsent(…) would be a good fit.