14.1. Spring Framework

14.2. Spring Cache

Redisson provides Redis based Spring Cache implementation made according to Spring Cache specification. Each Cache instance has two important parameters: ttl and maxIdleTime. Data is stored infinitely if these settings are not defined or equal to 0.

Config example:

  1. @Configuration
  2. @ComponentScan
  3. @EnableCaching
  4. public static class Application {
  5. @Bean(destroyMethod="shutdown")
  6. RedissonClient redisson() throws IOException {
  7. Config config = new Config();
  8. config.useClusterServers()
  9. .addNodeAddress("redis://127.0.0.1:7004", "redis://127.0.0.1:7001");
  10. return Redisson.create(config);
  11. }
  12. @Bean
  13. CacheManager cacheManager(RedissonClient redissonClient) {
  14. Map<String, CacheConfig> config = new HashMap<String, CacheConfig>();
  15. // create "testMap" cache with ttl = 24 minutes and maxIdleTime = 12 minutes
  16. config.put("testMap", new CacheConfig(24*60*1000, 12*60*1000));
  17. return new RedissonSpringCacheManager(redissonClient, config);
  18. }
  19. }

Cache configuration can be read from YAML configuration files:

  1. @Configuration
  2. @ComponentScan
  3. @EnableCaching
  4. public static class Application {
  5. @Bean(destroyMethod="shutdown")
  6. RedissonClient redisson(@Value("classpath:/redisson.yaml") Resource configFile) throws IOException {
  7. Config config = Config.fromYAML(configFile.getInputStream());
  8. return Redisson.create(config);
  9. }
  10. @Bean
  11. CacheManager cacheManager(RedissonClient redissonClient) throws IOException {
  12. return new RedissonSpringCacheManager(redissonClient, "classpath:/cache-config.yaml");
  13. }
  14. }

14.2.1 Spring Cache. Local cache and data partitioning

Redisson provides various Spring Cache managers with two important features:

local cache - so called near cache used to speed up read operations and avoid network roundtrips. It caches Spring Cache entries on Redisson side and executes read operations up to 45x faster in comparison with common implementation. Local cache instances with the same name connected to the same pub/sub channel. This channel is used for exchanging of update/invalidate events between all instances. Local cache store doesn’t use hashCode()/equals() methods of key object, instead it uses hash of serialized state.

data partitioning - although Spring Cache instance is cluster compatible its content isn’t scaled/partitioned across multiple Redis master nodes in cluster. Data partitioning allows to scale available memory, read/write operations and entry eviction process for individual Spring Cache instance in Redis cluster.

entry eviction - allows to define time to live or max idle time per map entry. Redis hash structure doesn’t support eviction thus it’s done on Redisson side through custom scheduled task which removes expired entries. Eviction task is started when the cache instance is created. If cache instance isn’t used and has expired entries it should be created to start the eviction process. This leads to extra Redis calls and eviction task per unique cache instance name.

advanced entry eviction - improved version of the entry eviction process. Doesn’t use an entry eviction task.

Below is complete list of available managers:

Class name Local
cache
Data
partitioning
Entry
eviction
Advanced
entry eviction
Ultra-fast
read/write
RedissonSpringCacheManager
open-source version
✔️
RedissonSpringCacheManager
Redisson PRO version
✔️ ✔️
RedissonSpringCacheV2Manager
available only in Redisson PRO
✔️ ✔️ ✔️
RedissonSpringLocalCachedCacheManager
available only in Redisson PRO
✔️ ✔️ ✔️
RedissonSpringLocalCachedCacheV2Manager
available only in Redisson PRO
✔️ ✔️ ✔️ ✔️
RedissonClusteredSpringCacheManager
available only in Redisson PRO
✔️ ✔️ ✔️
RedissonClusteredSpringLocalCachedCacheManager
available only in Redisson PRO
✔️ ✔️ ✔️ ✔️

Follow options object should be supplied during org.redisson.spring.cache.RedissonSpringLocalCachedCacheManager or org.redisson.spring.cache.RedissonClusteredSpringLocalCachedCacheManager initialization:

  1. LocalCachedMapOptions options = LocalCachedMapOptions.defaults()
  2. // Defines whether to store a cache miss into the local cache.
  3. // Default value is false.
  4. .storeCacheMiss(false);
  5. // Defines store mode of cache data.
  6. // Follow options are available:
  7. // LOCALCACHE - store data in local cache only.
  8. // LOCALCACHE_REDIS - store data in both Redis and local cache.
  9. .storeMode(StoreMode.LOCALCACHE_REDIS)
  10. // Defines Cache provider used as local cache store.
  11. // Follow options are available:
  12. // REDISSON - uses Redisson own implementation
  13. // CAFFEINE - uses Caffeine implementation
  14. .cacheProvider(CacheProvider.REDISSON)
  15. // Defines local cache eviction policy.
  16. // Follow options are available:
  17. // LFU - Counts how often an item was requested. Those that are used least often are discarded first.
  18. // LRU - Discards the least recently used items first
  19. // SOFT - Uses weak references, entries are removed by GC
  20. // WEAK - Uses soft references, entries are removed by GC
  21. // NONE - No eviction
  22. .evictionPolicy(EvictionPolicy.NONE)
  23. // If cache size is 0 then local cache is unbounded.
  24. .cacheSize(1000)
  25. // Used to load missed updates during any connection failures to Redis.
  26. // Since, local cache updates can't be get in absence of connection to Redis.
  27. // Follow reconnection strategies are available:
  28. // CLEAR - Clear local cache if map instance has been disconnected for a while.
  29. // LOAD - Store invalidated entry hash in invalidation log for 10 minutes
  30. // Cache keys for stored invalidated entry hashes will be removed
  31. // if LocalCachedMap instance has been disconnected less than 10 minutes
  32. // or whole cache will be cleaned otherwise.
  33. // NONE - Default. No reconnection handling
  34. .reconnectionStrategy(ReconnectionStrategy.NONE)
  35. // Used to synchronize local cache changes.
  36. // Follow sync strategies are available:
  37. // INVALIDATE - Default. Invalidate cache entry across all LocalCachedMap instances on map entry change
  38. // UPDATE - Insert/update cache entry across all LocalCachedMap instances on map entry change
  39. // NONE - No synchronizations on map changes
  40. .syncStrategy(SyncStrategy.INVALIDATE)
  41. // time to live for each map entry in local cache
  42. .timeToLive(10000)
  43. // or
  44. .timeToLive(10, TimeUnit.SECONDS)
  45. // max idle time for each map entry in local cache
  46. .maxIdle(10000)
  47. // or
  48. .maxIdle(10, TimeUnit.SECONDS);

Each Spring Cache instance has two important parameters: ttl and maxIdleTime and stores data infinitely if they are not defined or equal to 0.

Complete config example:

  1. @Configuration
  2. @ComponentScan
  3. @EnableCaching
  4. public static class Application {
  5. @Bean(destroyMethod="shutdown")
  6. RedissonClient redisson() throws IOException {
  7. Config config = new Config();
  8. config.useClusterServers()
  9. .addNodeAddress("redis://127.0.0.1:7004", "redis://127.0.0.1:7001");
  10. return Redisson.create(config);
  11. }
  12. @Bean
  13. CacheManager cacheManager(RedissonClient redissonClient) {
  14. Map<String, CacheConfig> config = new HashMap<String, CacheConfig>();
  15. // define local cache settings for "testMap" cache.
  16. // ttl = 48 minutes and maxIdleTime = 24 minutes for local cache entries
  17. LocalCachedMapOptions options = LocalCachedMapOptions.defaults()
  18. .evictionPolicy(EvictionPolicy.LFU)
  19. .timeToLive(48, TimeUnit.MINUTES)
  20. .maxIdle(24, TimeUnit.MINUTES);
  21. .cacheSize(1000);
  22. // create "testMap" Redis cache with ttl = 24 minutes and maxIdleTime = 12 minutes
  23. LocalCachedCacheConfig cfg = new LocalCachedCacheConfig(24*60*1000, 12*60*1000, options);
  24. // Max size of map stored in Redis
  25. cfg.setMaxSize(2000);
  26. config.put("testMap", cfg);
  27. return new RedissonSpringLocalCachedCacheManager(redissonClient, config);
  28. }
  29. }

Cache configuration could be read from YAML configuration files:

  1. @Configuration
  2. @ComponentScan
  3. @EnableCaching
  4. public static class Application {
  5. @Bean(destroyMethod="shutdown")
  6. RedissonClient redisson(@Value("classpath:/redisson.yaml") Resource configFile) throws IOException {
  7. Config config = Config.fromYAML(configFile.getInputStream());
  8. return Redisson.create(config);
  9. }
  10. @Bean
  11. CacheManager cacheManager(RedissonClient redissonClient) throws IOException {
  12. return new RedissonSpringLocalCachedCacheManager(redissonClient, "classpath:/cache-config.yaml");
  13. }
  14. }

14.2.2 Spring Cache. YAML config format

Below is the configuration of Spring Cache with name testMap in YAML format:

  1. ---
  2. testMap:
  3. ttl: 1440000
  4. maxIdleTime: 720000
  5. localCacheOptions:
  6. invalidationPolicy: "ON_CHANGE"
  7. evictionPolicy: "NONE"
  8. cacheSize: 0
  9. timeToLiveInMillis: 0
  10. maxIdleInMillis: 0

Please note: localCacheOptions settings are available for org.redisson.spring.cache.RedissonSpringLocalCachedCacheManager and org.redisson.spring.cache.RedissonSpringClusteredLocalCachedCacheManager classes only.

14.3. Hibernate Cache

Please find more information regarding this chapter here.

14.3.1. Hibernate Cache. Local cache and data partitioning

Please find more information regarding this chapter here.

14.4 JCache API (JSR-107) implementation

Redisson provides an implementation of JCache API (JSR-107) for Redis.

Below are examples of JCache API usage.

1. Using default config located at /redisson-jcache.yaml:

  1. MutableConfiguration<String, String> config = new MutableConfiguration<>();
  2. CacheManager manager = Caching.getCachingProvider().getCacheManager();
  3. Cache<String, String> cache = manager.createCache("namedCache", config);

2. Using config file with custom location:

  1. MutableConfiguration<String, String> config = new MutableConfiguration<>();
  2. // yaml config
  3. URI redissonConfigUri = getClass().getResource("redisson-jcache.yaml").toURI();
  4. CacheManager manager = Caching.getCachingProvider().getCacheManager(redissonConfigUri, null);
  5. Cache<String, String> cache = manager.createCache("namedCache", config);

3. Using Redisson’s config object:

  1. MutableConfiguration<String, String> jcacheConfig = new MutableConfiguration<>();
  2. Config redissonCfg = ...
  3. Configuration<String, String> config = RedissonConfiguration.fromConfig(redissonCfg, jcacheConfig);
  4. CacheManager manager = Caching.getCachingProvider().getCacheManager();
  5. Cache<String, String> cache = manager.createCache("namedCache", config);

4. Using Redisson instance object:

  1. MutableConfiguration<String, String> jcacheConfig = new MutableConfiguration<>();
  2. RedissonClient redisson = ...
  3. Configuration<String, String> config = RedissonConfiguration.fromInstance(redisson, jcacheConfig);
  4. CacheManager manager = Caching.getCachingProvider().getCacheManager();
  5. Cache<String, String> cache = manager.createCache("namedCache", config);

Read more here about Redisson configuration.

Provided implementation fully passes TCK tests. Here is the test module.

14.4.1 JCache API. Asynchronous, Reactive and RxJava3 interfaces

Along with usual JCache API, Redisson provides Asynchronous, Reactive and RxJava3 API.

Asynchronous interface. Each method returns org.redisson.api.RFuture object.
Example:

  1. MutableConfiguration<String, String> config = new MutableConfiguration<>();
  2. CacheManager manager = Caching.getCachingProvider().getCacheManager();
  3. Cache<String, String> cache = manager.createCache("myCache", config);
  4. CacheAsync<String, String> asyncCache = cache.unwrap(CacheAsync.class);
  5. RFuture<Void> putFuture = asyncCache.putAsync("1", "2");
  6. RFuture<String> getFuture = asyncCache.getAsync("1");

Reactive interface. Each method returns reactor.core.publisher.Mono object.
Example:

  1. MutableConfiguration<String, String> config = new MutableConfiguration<>();
  2. CacheManager manager = Caching.getCachingProvider().getCacheManager();
  3. Cache<String, String> cache = manager.createCache("myCache", config);
  4. CacheReactive<String, String> reactiveCache = cache.unwrap(CacheReactive.class);
  5. Mono<Void> putFuture = reactiveCache.put("1", "2");
  6. Mono<String> getFuture = reactiveCache.get("1");

RxJava3 interface. Each method returns one of the following object: io.reactivex.Completable, io.reactivex.Single, io.reactivex.Maybe.
Example:

  1. MutableConfiguration<String, String> config = new MutableConfiguration<>();
  2. CacheManager manager = Caching.getCachingProvider().getCacheManager();
  3. Cache<String, String> cache = manager.createCache("myCache", config);
  4. CacheRx<String, String> rxCache = cache.unwrap(CacheRx.class);
  5. Completable putFuture = rxCache.put("1", "2");
  6. Maybe<String> getFuture = rxCache.get("1");

14.4.2 JCache API. Local cache and data partitioning

Redisson provides JCache implementations with two important features:

local cache - so called near cache used to speed up read operations and avoid network roundtrips. It caches JCache entries on Redisson side and executes read operations up to 45x faster in comparison with common implementation. Local cache instances with the same name connected to the same pub/sub channel. This channel is used for exchanging of update/invalidate events between all instances. Local cache store doesn’t use hashCode()/equals() methods of key object, instead it uses hash of serialized state.

data partitioning - although JCache instance is cluster compatible its content isn’t scaled/partitioned across multiple Redis master nodes in cluster. Data partitioning allows to scale available memory, read/write operations and entry eviction process for individual JCache instance in Redis cluster.

Below is the complete list of available managers:

Local
cache
Data
partitioning
Ultra-fast
read/write
Fallback
mode
JCache
open-source version
JCache
Redisson PRO version
✔️ ✔️
JCache with local cache
available only in Redisson PRO
✔️ ✔️ ✔️
JCache with data partitioning
available only in Redisson PRO
✔️ ✔️ ✔️
JCache with local cache and data partitioning
available only in Redisson PRO
✔️ ✔️ ✔️ ✔️
1.1. Local cache configuration:
  1. LocalCacheConfiguration<String, String> configuration = new LocalCacheConfiguration<>()
  2. // Defines whether to store a cache miss into the local cache.
  3. // Default value is false.
  4. .storeCacheMiss(false);
  5. // Defines store mode of cache data.
  6. // Follow options are available:
  7. // LOCALCACHE - store data in local cache only and use Redis only for data update/invalidation.
  8. // LOCALCACHE_REDIS - store data in both Redis and local cache.
  9. .storeMode(StoreMode.LOCALCACHE_REDIS)
  10. // Defines Cache provider used as local cache store.
  11. // Follow options are available:
  12. // REDISSON - uses Redisson own implementation
  13. // CAFFEINE - uses Caffeine implementation
  14. .cacheProvider(CacheProvider.REDISSON)
  15. // Defines local cache eviction policy.
  16. // Follow options are available:
  17. // LFU - Counts how often an item was requested. Those that are used least often are discarded first.
  18. // LRU - Discards the least recently used items first
  19. // SOFT - Uses weak references, entries are removed by GC
  20. // WEAK - Uses soft references, entries are removed by GC
  21. // NONE - No eviction
  22. .evictionPolicy(EvictionPolicy.NONE)
  23. // If cache size is 0 then local cache is unbounded.
  24. .cacheSize(1000)
  25. // Used to load missed updates during any connection failures to Redis.
  26. // Since, local cache updates can't be get in absence of connection to Redis.
  27. // Follow reconnection strategies are available:
  28. // CLEAR - Clear local cache if map instance has been disconnected for a while.
  29. // LOAD - Store invalidated entry hash in invalidation log for 10 minutes
  30. // Cache keys for stored invalidated entry hashes will be removed
  31. // if LocalCachedMap instance has been disconnected less than 10 minutes
  32. // or whole cache will be cleaned otherwise.
  33. // NONE - Default. No reconnection handling
  34. .reconnectionStrategy(ReconnectionStrategy.NONE)
  35. // Used to synchronize local cache changes.
  36. // Follow sync strategies are available:
  37. // INVALIDATE - Default. Invalidate cache entry across all LocalCachedMap instances on map entry change
  38. // UPDATE - Insert/update cache entry across all LocalCachedMap instances on map entry change
  39. // NONE - No synchronizations on map changes
  40. .syncStrategy(SyncStrategy.INVALIDATE)
  41. // time to live for each map entry in local cache
  42. .timeToLive(10000)
  43. // or
  44. .timeToLive(10, TimeUnit.SECONDS)
  45. // max idle time for each map entry in local cache
  46. .maxIdle(10000)
  47. // or
  48. .maxIdle(10, TimeUnit.SECONDS);
1.2. Local cache usage examples:
  1. LocalCacheConfiguration<String, String> config = new LocalCacheConfiguration<>();
  2. .setEvictionPolicy(EvictionPolicy.LFU)
  3. .setTimeToLive(48, TimeUnit.MINUTES)
  4. .setMaxIdle(24, TimeUnit.MINUTES);
  5. .setCacheSize(1000);
  6. CacheManager manager = Caching.getCachingProvider().getCacheManager();
  7. Cache<String, String> cache = manager.createCache("myCache", config);
  8. // or
  9. URI redissonConfigUri = getClass().getResource("redisson-jcache.yaml").toURI();
  10. CacheManager manager = Caching.getCachingProvider().getCacheManager(redissonConfigUri, null);
  11. Cache<String, String> cache = manager.createCache("myCache", config);
  12. // or
  13. Config redissonCfg = ...
  14. Configuration<String, String> rConfig = RedissonConfiguration.fromConfig(redissonCfg, config);
  15. CacheManager manager = Caching.getCachingProvider().getCacheManager();
  16. Cache<String, String> cache = manager.createCache("namedCache", rConfig);
1.3. Data partitioning usage examples:
  1. ClusteredConfiguration<String, String> config = new ClusteredConfiguration<>();
  2. CacheManager manager = Caching.getCachingProvider().getCacheManager();
  3. Cache<String, String> cache = manager.createCache("myCache", config);
  4. // or
  5. URI redissonConfigUri = getClass().getResource("redisson-jcache.yaml").toURI();
  6. CacheManager manager = Caching.getCachingProvider().getCacheManager(redissonConfigUri, null);
  7. Cache<String, String> cache = manager.createCache("myCache", config);
  8. // or
  9. Config redissonCfg = ...
  10. Configuration<String, String> rConfig = RedissonConfiguration.fromConfig(redissonCfg, config);
  11. CacheManager manager = Caching.getCachingProvider().getCacheManager();
  12. Cache<String, String> cache = manager.createCache("namedCache", rConfig);
1.4. Local cache with data partitioning configuration:
  1. ClusteredLocalCacheConfiguration<String, String> configuration = new ClusteredLocalCacheConfiguration<>()
  2. // Defines whether to store a cache miss into the local cache.
  3. // Default value is false.
  4. .storeCacheMiss(false);
  5. // Defines store mode of cache data.
  6. // Follow options are available:
  7. // LOCALCACHE - store data in local cache only and use Redis only for data update/invalidation.
  8. // LOCALCACHE_REDIS - store data in both Redis and local cache.
  9. .storeMode(StoreMode.LOCALCACHE_REDIS)
  10. // Defines Cache provider used as local cache store.
  11. // Follow options are available:
  12. // REDISSON - uses Redisson own implementation
  13. // CAFFEINE - uses Caffeine implementation
  14. .cacheProvider(CacheProvider.REDISSON)
  15. // Defines local cache eviction policy.
  16. // Follow options are available:
  17. // LFU - Counts how often an item was requested. Those that are used least often are discarded first.
  18. // LRU - Discards the least recently used items first
  19. // SOFT - Uses weak references, entries are removed by GC
  20. // WEAK - Uses soft references, entries are removed by GC
  21. // NONE - No eviction
  22. .evictionPolicy(EvictionPolicy.NONE)
  23. // If cache size is 0 then local cache is unbounded.
  24. .cacheSize(1000)
  25. // Used to load missed updates during any connection failures to Redis.
  26. // Since, local cache updates can't be get in absence of connection to Redis.
  27. // Follow reconnection strategies are available:
  28. // CLEAR - Clear local cache if map instance has been disconnected for a while.
  29. // LOAD - Store invalidated entry hash in invalidation log for 10 minutes
  30. // Cache keys for stored invalidated entry hashes will be removed
  31. // if LocalCachedMap instance has been disconnected less than 10 minutes
  32. // or whole cache will be cleaned otherwise.
  33. // NONE - Default. No reconnection handling
  34. .reconnectionStrategy(ReconnectionStrategy.NONE)
  35. // Used to synchronize local cache changes.
  36. // Follow sync strategies are available:
  37. // INVALIDATE - Default. Invalidate cache entry across all LocalCachedMap instances on map entry change
  38. // UPDATE - Insert/update cache entry across all LocalCachedMap instances on map entry change
  39. // NONE - No synchronizations on map changes
  40. .syncStrategy(SyncStrategy.INVALIDATE)
  41. // time to live for each map entry in local cache
  42. .timeToLive(10000)
  43. // or
  44. .timeToLive(10, TimeUnit.SECONDS)
  45. // max idle time for each map entry in local cache
  46. .maxIdle(10000)
  47. // or
  48. .maxIdle(10, TimeUnit.SECONDS);
1.5. Local cache with data partitioning usage examples:
  1. ClusteredLocalCacheConfiguration<String, String> config = new ClusteredLocalCacheConfiguration<>();
  2. CacheManager manager = Caching.getCachingProvider().getCacheManager();
  3. Cache<String, String> cache = manager.createCache("myCache", config);
  4. // or
  5. URI redissonConfigUri = getClass().getResource("redisson-jcache.yaml").toURI();
  6. CacheManager manager = Caching.getCachingProvider().getCacheManager(redissonConfigUri, null);
  7. Cache<String, String> cache = manager.createCache("myCache", config);
  8. // or
  9. Config redissonCfg = ...
  10. Configuration<String, String> rConfig = RedissonConfiguration.fromConfig(redissonCfg, config);
  11. CacheManager manager = Caching.getCachingProvider().getCacheManager();
  12. Cache<String, String> cache = manager.createCache("namedCache", rConfig);

14.4.3. Open Liberty or WebSphere Liberty integration

Distributed Cache configuration example:

  1. <library id="jCacheVendorLib">
  2. <file name="${shared.resource.dir}/redisson-all-3.31.0.jar"/>
  3. </library>
  4. <cache id="io.openliberty.cache.authentication" name="io.openliberty.cache.authentication"
  5. cacheManagerRef="CacheManager" />
  6. <cacheManager id="CacheManager" uri="file:${server.config.dir}/redisson-jcache.yaml">
  7. <properties fallback="true"/>
  8. <cachingProvider jCacheLibraryRef="jCacheVendorLib"/>
  9. </cacheManager>

Distributed Session persistence configuration example:

  1. <featureManager>
  2. <feature>servlet-6.0</feature>
  3. <feature>sessionCache-1.0</feature>
  4. </featureManager>
  5. <httpEndpoint httpPort="${http.port}" httpsPort="${https.port}"
  6. id="defaultHttpEndpoint" host="*" />
  7. <library id="jCacheVendorLib">
  8. <file name="${shared.resource.dir}/redisson-all-3.31.0.jar"/>
  9. </library>
  10. <httpSessionCache cacheManagerRef="CacheManager"/>
  11. <cacheManager id="CacheManager" uri="file:${server.config.dir}/redisson-jcache.yaml">
  12. <properties fallback="true"/>
  13. <cachingProvider jCacheLibraryRef="jCacheVendorLib"/>
  14. </cacheManager>

Settings below are available only in Redisson PRO edition.

Follow settings are available per JCache instance:

Parameter fallback
Description Skip errors if Redis cache is unavailable
Default value false
Parameter implementation
Description Cache implementation.
cache - standard implementation
clustered-local-cache - data partitioning and local cache support
local-cache - local cache support
clustered-cache - data partitioning support
Default value cache
Parameter localcache.store_cache_miss
Description Defines whether to store a cache miss into the local cache.
Default value false
Parameter localcache.cache_provider
Description Cache provider used as local cache store.
REDISSON and CAFFEINE providers are available.
Default value REDISSON
Parameter localcache.store_mode
Description Store mode of cache data.
LOCALCACHE - store data in local cache only and use Redis only for data update/invalidation
LOCALCACHE_REDIS - store data in both Redis and local cache
Default value LOCALCACHE
Parameter localcache.max_idle_time
Description Max idle time per entry in local cache. Defined in milliseconds.
0 value means this setting doesn’t affect expiration
Default value 0
Parameter localcache.time_to_live
Description Time to live per entry in local cache. Defined in milliseconds.
0 value means this setting doesn’t affect expiration
Default value 0
Parameter localcache.eviction_policy
Description Eviction policy applied to local cache entries when cache size limit reached.
LFU, LRU, SOFT, WEAK and NONE policies are available.
Default value NONE
Parameter localcache.sync_strategy
Description Sync strategy used to synchronize local cache changes across all instances.
INVALIDATE - Invalidate cache entry across all LocalCachedMap instances on map entry change
UPDATE - Update cache entry across all LocalCachedMap instances on map entry change
NONE - No synchronizations on map changes
Default value INVALIDATE
Parameter localcache.reconnection_strategy
Description Reconnection strategy used to load missed local cache updates through Hibernate during any connection failures to Redis.
CLEAR - Clear local cache if map instance has been disconnected for a while
LOAD - Store invalidated entry hash in invalidation log for 10 minutes. Cache keys for stored invalidated entry hashes will be removed if LocalCachedMap instance has been disconnected less than 10 minutes or whole cache will be cleaned otherwise
NONE - No reconnection handling
Default value NONE
Parameter localcache.size
Description Max size of local cache. Superfluous entries in Redis are evicted using defined eviction policy.
0 value means unbounded cache.
Default value 0

14.5. MyBatis Cache

Please find more information regarding this chapter here.

14.5.1. MyBatis Cache. Local cache and data partitioning

Please find more information regarding this chapter here.

14.6. Tomcat Redis Session Manager

Please find more information regarding this chapter here.

14.7. Spring Session

Please note that Redis notify-keyspace-events setting should contain Exg letters to make Spring Session integration work.

Ensure you have Spring Session library in your classpath, add it if necessary:

Maven

  1. <dependency>
  2. <groupId>org.springframework.session</groupId>
  3. <artifactId>spring-session-core</artifactId>
  4. <version>3.2.1</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.redisson</groupId>
  8. <artifactId>redisson-spring-data-32</artifactId>
  9. <version>3.31.0</version>
  10. </dependency>

Gradle

  1. compile 'org.springframework.session:spring-session-core:3.2.1'
  2. compile 'org.redisson:redisson-spring-data-32:3.31.0'

Usage example of Spring Http Session configuration:

Add configuration class which extends AbstractHttpSessionApplicationInitializer class:

  1. @Configuration
  2. @EnableRedisHttpSession
  3. public class SessionConfig extends AbstractHttpSessionApplicationInitializer {
  4. @Bean
  5. public RedissonConnectionFactory redissonConnectionFactory(RedissonClient redisson) {
  6. return new RedissonConnectionFactory(redisson);
  7. }
  8. @Bean(destroyMethod = "shutdown")
  9. public RedissonClient redisson(@Value("classpath:/redisson.yaml") Resource configFile) throws IOException {
  10. Config config = Config.fromYAML(configFile.getInputStream());
  11. return Redisson.create(config);
  12. }
  13. }

Usage example of Spring WebFlux’s Session configuration:

Add configuration class which extends AbstractReactiveWebInitializer class:

  1. @Configuration
  2. @EnableRedisWebSession
  3. public class SessionConfig extends AbstractReactiveWebInitializer {
  4. @Bean
  5. public RedissonConnectionFactory redissonConnectionFactory(RedissonClient redisson) {
  6. return new RedissonConnectionFactory(redisson);
  7. }
  8. @Bean(destroyMethod = "shutdown")
  9. public RedissonClient redisson(@Value("classpath:/redisson.yaml") Resource configFile) throws IOException {
  10. Config config = Config.fromYAML(configFile.getInputStream());
  11. return Redisson.create(config);
  12. }
  13. }

Usage example with Spring Boot configuration:

  1. Add Spring Session Data Redis library in classpath:

    Maven

    1. <dependency>
    2. <groupId>org.springframework.session</groupId>
    3. <artifactId>spring-session-data-redis</artifactId>
    4. <version>3.2.1</version>
    5. </dependency>

    Gradle

    1. compile 'org.springframework.session:spring-session-data-redis:3.2.1'
  2. Add Redisson Spring Data Redis library in classpath:

    Maven

    1. <dependency>
    2. <groupId>org.redisson</groupId>
    3. <artifactId>redisson-spring-data-32</artifactId>
    4. <version>3.31.0</version>
    5. </dependency>

    Gradle

    1. compile 'org.redisson:redisson-spring-data-32:3.31.0'
  3. Define follow properties in spring-boot settings

  1. spring.session.store-type=redis
  2. spring.redis.redisson.file=classpath:redisson.yaml
  3. spring.session.timeout.seconds=900

Try Redisson PRO with ultra-fast performance and support by SLA.

14.8. Spring Transaction Manager

Redisson provides implementation of both org.springframework.transaction.PlatformTransactionManager and org.springframework.transaction.ReactiveTransactionManager interfaces to participant in Spring transactions. See also Transactions section.

Usage example of Spring Transaction Management:

  1. @Configuration
  2. @EnableTransactionManagement
  3. public class RedissonTransactionContextConfig {
  4. @Bean
  5. public TransactionalBean transactionBean() {
  6. return new TransactionalBean();
  7. }
  8. @Bean
  9. public RedissonTransactionManager transactionManager(RedissonClient redisson) {
  10. return new RedissonTransactionManager(redisson);
  11. }
  12. @Bean(destroyMethod="shutdown")
  13. public RedissonClient redisson(@Value("classpath:/redisson.yaml") Resource configFile) throws IOException {
  14. Config config = Config.fromYAML(configFile.getInputStream());
  15. return Redisson.create(config);
  16. }
  17. }
  18. public class TransactionalBean {
  19. @Autowired
  20. private RedissonTransactionManager transactionManager;
  21. @Transactional
  22. public void commitData() {
  23. RTransaction transaction = transactionManager.getCurrentTransaction();
  24. RMap<String, String> map = transaction.getMap("test1");
  25. map.put("1", "2");
  26. }
  27. }

Usage example of Reactive Spring Transaction Management:

  1. @Configuration
  2. @EnableTransactionManagement
  3. public class RedissonReactiveTransactionContextConfig {
  4. @Bean
  5. public TransactionalBean transactionBean() {
  6. return new TransactionalBean();
  7. }
  8. @Bean
  9. public ReactiveRedissonTransactionManager transactionManager(RedissonReactiveClient redisson) {
  10. return new ReactiveRedissonTransactionManager(redisson);
  11. }
  12. @Bean(destroyMethod="shutdown")
  13. public RedissonReactiveClient redisson(@Value("classpath" +
  14. "redisson.yaml") Resource configFile) throws IOException {
  15. Config config = Config.fromYAML(configFile.getInputStream());
  16. return Redisson.createReactive(config);
  17. }
  18. }
  19. public class TransactionalBean {
  20. @Autowired
  21. private ReactiveRedissonTransactionManager transactionManager;
  22. @Transactional
  23. public Mono<Void> commitData() {
  24. Mono<RTransactionReactive> transaction = transactionManager.getCurrentTransaction();
  25. return transaction.flatMap(t -> {
  26. RMapReactive<String, String> map = t.getMap("test1");
  27. return map.put("1", "2");
  28. }).then();
  29. }
  30. }

14.9. Spring Cloud Stream

This feature is available only in Redisson PRO edition.

To use Redis binder with Redisson you need to add Spring Cloud Stream Binder library in classpath:

Maven

  1. <dependency>
  2. <groupId>pro.redisson</groupId>
  3. <artifactId>spring-cloud-stream-binder-redisson</artifactId>
  4. <version>3.31.0</version>
  5. </dependency>

Gradle

  1. compile 'pro.redisson:spring-cloud-stream-binder-redisson:3.31.0'

Compatible with Spring versions below.

Spring Cloud Stream Spring Cloud Spring Boot
4.1.x 2023.0.x 3.0.x, 3.1.x, 3.2.x
4.0.x 2022.0.x 3.0.x, 3.1.x, 3.2.x
3.2.x 2021.0.x 2.6.x, 2.7.x (Starting with 2021.0.3 of Spring Cloud)
3.1.x 2020.0.x 2.4.x, 2.5.x (Starting with 2020.0.3 of Spring Cloud)

14.9.1 Receiving messages

Register the input binder (an event sink) for receiving messages as follows:

  1. @Bean
  2. public Consumer<MyObject> receiveMessage() {
  3. return obj -> {
  4. // consume received object ...
  5. };
  6. }

Define channel id in the configuration file application.properties. Example for receiveMessage bean defined above connected to my-channel channel:

  1. spring.cloud.stream.bindings.receiveMessage-in-0.destination=my-channel

14.9.2 Publishing messages

Register the output binder (an event source) for publishing messages as follows:

  1. @Bean
  2. public Supplier<MyObject> feedSupplier() {
  3. return () -> {
  4. // ...
  5. return new MyObject();
  6. };
  7. }

Define channel id in the configuration file application.properties. Example for feedSupplier bean defined above connected to my-channel channel:

  1. spring.cloud.stream.bindings.feedSupplier-out-0.destination=my-channel
  2. spring.cloud.stream.bindings.feedSupplier-out-0.producer.useNativeEncoding=true

14.10. Spring Data Redis

Please find information regarding this chapter here.

14.11. Spring Boot Starter

Please find the information regarding this chapter here.

14.12. Micronaut

Please find the information regarding this chapter here.

14.13. Quarkus

Please find the information regarding this chapter here.

14.14. Helidon

Please find the information regarding this chapter here.