Integration with Spring
Spring Boot Starter¶
Integrates Redisson with Spring Boot library. Depends on Spring Data Redis module.
Supports Spring Boot 1.3.x - 3.3.x
Usage¶
1. Add redisson-spring-boot-starter
dependency into your project:
Maven
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.36.0</version>
</dependency>
Gradle
redisson-spring-boot-starter
depends on redisson-spring-data
module compatible with the latest version of Spring Boot. Downgrade redisson-spring-data
module if necessary to support previous Spring Boot versions:
redisson-spring-data module name |
Spring Boot version |
---|---|
redisson-spring-data-16 | 1.3.y |
redisson-spring-data-17 | 1.4.y |
redisson-spring-data-18 | 1.5.y |
redisson-spring-data-2x | 2.x.y |
redisson-spring-data-3x | 3.x.y |
For Gradle, you can downgrade to redisson-spring-data-27
this way:
implementation ("org.redisson:redisson-spring-boot-starter:3.36.0") {
exclude group: 'org.redisson', module: 'redisson-spring-data-33'
}
implementation "org.redisson:redisson-spring-data-27:3.36.0"
2. Add settings into application.settings
file
Using common Spring Boot 3.x+ settings:
spring:
data:
redis:
database:
host:
port:
password:
ssl:
timeout:
connectTimeout:
clientName:
cluster:
nodes:
sentinel:
master:
nodes:
Using common Spring Boot up to 2.7.x settings:
spring:
redis:
database:
host:
port:
password:
ssl:
timeout:
connectTimeout:
clientName:
cluster:
nodes:
sentinel:
master:
nodes:
Using Redisson config file: (single mode, replicated mode, cluster mode, sentinel mode, proxy mode, multi cluster mode, multi sentinel mode)
Using Redisson settings: (single mode, replicated mode, cluster mode, sentinel mode, proxy mode, multi cluster mode, multi sentinel mode)
spring:
redis:
redisson:
config: |
clusterServersConfig:
idleConnectionTimeout: 10000
connectTimeout: 10000
timeout: 3000
retryAttempts: 3
retryInterval: 1500
failedSlaveReconnectionInterval: 3000
failedSlaveCheckInterval: 60000
password: null
subscriptionsPerConnection: 5
clientName: null
loadBalancer: !<org.redisson.connection.balancer.RoundRobinLoadBalancer> {}
subscriptionConnectionMinimumIdleSize: 1
subscriptionConnectionPoolSize: 50
slaveConnectionMinimumIdleSize: 24
slaveConnectionPoolSize: 64
masterConnectionMinimumIdleSize: 24
masterConnectionPoolSize: 64
readMode: "SLAVE"
subscriptionMode: "SLAVE"
nodeAddresses:
- "redis://127.0.0.1:7004"
- "redis://127.0.0.1:7001"
- "redis://127.0.0.1:7000"
scanInterval: 1000
pingConnectionInterval: 0
keepAlive: false
tcpNoDelay: false
threads: 16
nettyThreads: 32
codec: !<org.redisson.codec.Kryo5Codec> {}
transportMode: "NIO"
3. Available Spring Beans:
RedissonClient
RedissonRxClient
RedissonReactiveClient
RedisTemplate
ReactiveRedisTemplate
Upgrade to Redisson PRO with advanced features.
FAQ¶
Q: How to replace Netty version brought by Spring Boot?
You need to define netty version in properties section of your Maven project.
Q: How to disable Redisson?
You may not have Redis or Valkey in some environments. In this case Redisson can be disabled:
- Using Annotations
Spring Boot 2.7+ Spring Boot up to 2.6 - Using application.yml file
Spring Boot 2.7+ Spring Boot up to 2.6
Spring Cache¶
Redisson provides various Spring Cache implementations. 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:
@Configuration
@ComponentScan
@EnableCaching
public static class Application {
@Bean(destroyMethod="shutdown")
RedissonClient redisson() throws IOException {
Config config = new Config();
config.useClusterServers()
.addNodeAddress("redis://127.0.0.1:7004", "redis://127.0.0.1:7001");
return Redisson.create(config);
}
@Bean
CacheManager cacheManager(RedissonClient redissonClient) {
Map<String, CacheConfig> config = new HashMap<String, CacheConfig>();
// create "testMap" cache with ttl = 24 minutes and maxIdleTime = 12 minutes
config.put("testMap", new CacheConfig(24*60*1000, 12*60*1000));
return new RedissonSpringCacheManager(redissonClient, config);
}
}
Cache configuration can be read from YAML configuration files:
@Configuration
@ComponentScan
@EnableCaching
public static class Application {
@Bean(destroyMethod="shutdown")
RedissonClient redisson(@Value("classpath:/redisson.yaml") Resource configFile) throws IOException {
Config config = Config.fromYAML(configFile.getInputStream());
return Redisson.create(config);
}
@Bean
CacheManager cacheManager(RedissonClient redissonClient) throws IOException {
return new RedissonSpringCacheManager(redissonClient, "classpath:/cache-config.yaml");
}
}
Eviction, 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 Map 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 Map object is cluster compatible its content isn't scaled/partitioned across multiple Redis or Valkey master nodes in cluster. Data partitioning allows to scale available memory, read/write operations and entry eviction process for individual Map instance in cluster.
Scripted eviction
Allows to define time to live
or max idle time
parameters per map entry. Eviction is done on Redisson side through a custom scheduled task which removes expired entries using Lua script. Eviction task is started once per unique object name at the moment of getting Map instance. If instance isn't used and has expired entries it should be get again to start the eviction process. This leads to extra Redis or Valkey calls and eviction task per unique map object name.
Entries are cleaned time to time by org.redisson.eviction.EvictionScheduler
. By default, it removes 100 expired entries at a time. This can be changed through cleanUpKeysAmount setting. Task launch time tuned automatically and depends on expired entries amount deleted in previous time and varies between 5 second to 30 minutes by default. This time interval can be changed through minCleanUpDelay and maxCleanUpDelay. For example, if clean task deletes 100 entries each time it will be executed every 5 seconds (minimum execution delay). But if current expired entries amount is lower than previous one then execution delay will be increased by 1.5 times and decreased otherwise.
Available implementations:
Class name | Local cache |
Data partitioning |
Ultra-fast read/write |
---|---|---|---|
RedissonSpringCacheManager open-source version |
❌ | ❌ | ❌ |
RedissonSpringCacheManager Redisson PRO version |
❌ | ❌ | ✔️ |
RedissonSpringLocalCachedCacheManager available only in Redisson PRO |
✔️ | ❌ | ✔️ |
RedissonClusteredSpringCacheManager available only in Redisson PRO |
❌ | ✔️ | ✔️ |
RedissonClusteredSpringLocalCachedCacheManager available only in Redisson PRO |
✔️ | ✔️ | ✔️ |
Advanced eviction
Allows to define time to live
parameter per map entry. Doesn't use an entry eviction task, entries are cleaned on Redis or Valkey side.
Available implementations:
Class name | Local cache |
Data partitioning |
Ultra-fast read/write |
---|---|---|---|
RedissonSpringCacheV2Manager available only in Redisson PRO |
❌ | ✔️ | ✔️ |
RedissonSpringLocalCachedCacheV2Manager available only in Redisson PRO |
✔️ | ✔️ | ✔️ |
Native eviction
Allows to define time to live
parameter per map entry. Doesn't use an entry eviction task, entries are cleaned on Redis side.
Requires Redis 7.4+.
Available implementations:
Class name | Local cache |
Data partitioning |
Ultra-fast read/write |
---|---|---|---|
RedissonSpringCacheNativeManager open-source version |
❌ | ❌ | ❌ |
RedissonSpringCacheNativeManager Redisson PRO version |
❌ | ❌ | ✔️ |
RedissonSpringLocalCachedCacheNativeManager available only in Redisson PRO |
✔️ | ❌ | ✔️ |
RedissonClusteredSpringCacheNativeManager available only in Redisson PRO |
❌ | ✔️ | ✔️ |
Local cache
Follow options object can be supplied during local cached managers initialization:
LocalCachedMapOptions options = LocalCachedMapOptions.defaults()
// Defines whether to store a cache miss into the local cache.
// Default value is false.
.storeCacheMiss(false);
// Defines store mode of cache data.
// Follow options are available:
// LOCALCACHE - store data in local cache only.
// LOCALCACHE_REDIS - store data in both Redis or Valkey and local cache.
.storeMode(StoreMode.LOCALCACHE_REDIS)
// Defines Cache provider used as local cache store.
// Follow options are available:
// REDISSON - uses Redisson own implementation
// CAFFEINE - uses Caffeine implementation
.cacheProvider(CacheProvider.REDISSON)
// Defines local cache eviction policy.
// Follow options are available:
// LFU - Counts how often an item was requested. Those that are used least often are discarded first.
// LRU - Discards the least recently used items first
// SOFT - Uses weak references, entries are removed by GC
// WEAK - Uses soft references, entries are removed by GC
// NONE - No eviction
.evictionPolicy(EvictionPolicy.NONE)
// If cache size is 0 then local cache is unbounded.
.cacheSize(1000)
// Used to load missed updates during any connection failures to Redis.
// Since, local cache updates can't be get in absence of connection to Redis.
// Follow reconnection strategies are available:
// 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 - Default. No reconnection handling
.reconnectionStrategy(ReconnectionStrategy.NONE)
// Used to synchronize local cache changes.
// Follow sync strategies are available:
// INVALIDATE - Default. Invalidate cache entry across all LocalCachedMap instances on map entry change
// UPDATE - Insert/update cache entry across all LocalCachedMap instances on map entry change
// NONE - No synchronizations on map changes
.syncStrategy(SyncStrategy.INVALIDATE)
// time to live for each map entry in local cache
.timeToLive(10000)
// or
.timeToLive(10, TimeUnit.SECONDS)
// max idle time for each map entry in local cache
.maxIdle(10000)
// or
.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:
@Configuration
@ComponentScan
@EnableCaching
public static class Application {
@Bean(destroyMethod="shutdown")
RedissonClient redisson() throws IOException {
Config config = new Config();
config.useClusterServers()
.addNodeAddress("redis://127.0.0.1:7004", "redis://127.0.0.1:7001");
return Redisson.create(config);
}
@Bean
CacheManager cacheManager(RedissonClient redissonClient) {
Map<String, CacheConfig> config = new HashMap<String, CacheConfig>();
// define local cache settings for "testMap" cache.
// ttl = 48 minutes and maxIdleTime = 24 minutes for local cache entries
LocalCachedMapOptions options = LocalCachedMapOptions.defaults()
.evictionPolicy(EvictionPolicy.LFU)
.timeToLive(48, TimeUnit.MINUTES)
.maxIdle(24, TimeUnit.MINUTES);
.cacheSize(1000);
// create "testMap" Redis or Valkey cache with ttl = 24 minutes and maxIdleTime = 12 minutes
LocalCachedCacheConfig cfg = new LocalCachedCacheConfig(24*60*1000, 12*60*1000, options);
// Max size of map stored in Redis
cfg.setMaxSize(2000);
config.put("testMap", cfg);
return new RedissonSpringLocalCachedCacheManager(redissonClient, config);
// or
return new RedissonSpringLocalCachedCacheNativeManager(redissonClient, config);
// or
return new RedissonSpringLocalCachedCacheV2Manager(redissonClient, config);
// or
return new RedissonClusteredSpringLocalCachedCacheManager(redissonClient, config);
}
}
Cache configuration could be read from YAML configuration files:
@Configuration
@ComponentScan
@EnableCaching
public static class Application {
@Bean(destroyMethod="shutdown")
RedissonClient redisson(@Value("classpath:/redisson.yaml") Resource configFile) throws IOException {
Config config = Config.fromYAML(configFile.getInputStream());
return Redisson.create(config);
}
@Bean
CacheManager cacheManager(RedissonClient redissonClient) throws IOException {
return new RedissonSpringLocalCachedCacheManager(redissonClient, "classpath:/cache-config.yaml");
}
}
YAML config format¶
Below is the configuration of Spring Cache with name testMap
in YAML format:
---
testMap:
ttl: 1440000
maxIdleTime: 720000
localCacheOptions:
invalidationPolicy: "ON_CHANGE"
evictionPolicy: "NONE"
cacheSize: 0
timeToLiveInMillis: 0
maxIdleInMillis: 0
Please note: localCacheOptions
settings are available for org.redisson.spring.cache.RedissonSpringLocalCachedCacheManager
and org.redisson.spring.cache.RedissonSpringClusteredLocalCachedCacheManager
classes only.
Spring Session¶
Please note that Redis or Valkey 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
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-core</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-data-33</artifactId>
<version>3.36.0</version>
</dependency>
Gradle
compile 'org.springframework.session:spring-session-core:3.2.1'
compile 'org.redisson:redisson-spring-data-33:3.36.0'
Spring Http Session configuration¶
Add configuration class which extends AbstractHttpSessionApplicationInitializer
class:
@Configuration
@EnableRedisHttpSession
public class SessionConfig extends AbstractHttpSessionApplicationInitializer {
@Bean
public RedissonConnectionFactory redissonConnectionFactory(RedissonClient redisson) {
return new RedissonConnectionFactory(redisson);
}
@Bean(destroyMethod = "shutdown")
public RedissonClient redisson(@Value("classpath:/redisson.yaml") Resource configFile) throws IOException {
Config config = Config.fromYAML(configFile.getInputStream());
return Redisson.create(config);
}
}
Spring WebFlux’s Session configuration¶
Add configuration class which extends AbstractReactiveWebInitializer
class:
@Configuration
@EnableRedisWebSession
public class SessionConfig extends AbstractReactiveWebInitializer {
@Bean
public RedissonConnectionFactory redissonConnectionFactory(RedissonClient redisson) {
return new RedissonConnectionFactory(redisson);
}
@Bean(destroyMethod = "shutdown")
public RedissonClient redisson(@Value("classpath:/redisson.yaml") Resource configFile) throws IOException {
Config config = Config.fromYAML(configFile.getInputStream());
return Redisson.create(config);
}
}
Spring Boot configuration¶
- Add Spring Session Data Redis library in classpath:
Maven: Gradle: - Add Redisson Spring Data Redis library in classpath:
Maven: Gradle: - Define follow properties in spring-boot settings
Upgrade to Redisson PRO with advanced features.
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.
Spring Transaction Management¶
@Configuration
@EnableTransactionManagement
public class RedissonTransactionContextConfig {
@Bean
public TransactionalBean transactionBean() {
return new TransactionalBean();
}
@Bean
public RedissonTransactionManager transactionManager(RedissonClient redisson) {
return new RedissonTransactionManager(redisson);
}
@Bean(destroyMethod="shutdown")
public RedissonClient redisson(@Value("classpath:/redisson.yaml") Resource configFile) throws IOException {
Config config = Config.fromYAML(configFile.getInputStream());
return Redisson.create(config);
}
}
public class TransactionalBean {
@Autowired
private RedissonTransactionManager transactionManager;
@Transactional
public void commitData() {
RTransaction transaction = transactionManager.getCurrentTransaction();
RMap<String, String> map = transaction.getMap("test1");
map.put("1", "2");
}
}
Reactive Spring Transaction Management¶
@Configuration
@EnableTransactionManagement
public class RedissonReactiveTransactionContextConfig {
@Bean
public TransactionalBean transactionBean() {
return new TransactionalBean();
}
@Bean
public ReactiveRedissonTransactionManager transactionManager(RedissonReactiveClient redisson) {
return new ReactiveRedissonTransactionManager(redisson);
}
@Bean(destroyMethod="shutdown")
public RedissonReactiveClient redisson(@Value("classpath:/redisson.yaml") Resource configFile) throws IOException {
Config config = Config.fromYAML(configFile.getInputStream());
return Redisson.createReactive(config);
}
}
public class TransactionalBean {
@Autowired
private ReactiveRedissonTransactionManager transactionManager;
@Transactional
public Mono<Void> commitData() {
Mono<RTransactionReactive> transaction = transactionManager.getCurrentTransaction();
return transaction.flatMap(t -> {
RMapReactive<String, String> map = t.getMap("test1");
return map.put("1", "2");
}).then();
}
}
Spring Cloud Stream¶
This feature is available only in Redisson PRO edition.
Redisson implements Spring Cloud Stream integration based on the reliable Redis Stream structure for message delivery. To use Redis binder with Redisson you need to add Spring Cloud Stream Binder library in classpath:
Maven:
<dependency>
<groupId>pro.redisson</groupId>
<artifactId>spring-cloud-stream-binder-redisson</artifactId>
<version>3.36.0</version>
</dependency>
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) |
Receiving messages¶
Register the input binder (an event sink) for receiving messages as follows:
@Bean
public Consumer<MyObject> receiveMessage() {
return obj -> {
// consume received object ...
};
}
Define channel id in the configuration file application.properties
. Example for receiveMessage
bean defined above connected to my-channel
channel:
Publishing messages¶
Register the output binder (an event source) for publishing messages as follows:
Define channel id in the configuration file application.properties
. Example for feedSupplier
bean defined above connected to my-channel
channel:
spring.cloud.stream.bindings.feedSupplier-out-0.destination=my-channel
spring.cloud.stream.bindings.feedSupplier-out-0.producer.useNativeEncoding=true
Spring Data Redis¶
Integrates Redisson with Spring Data Redis library. Implements Spring Data's RedisConnectionFactory
and ReactiveRedisConnectionFactory
interfaces and allows to interact with Redis through RedisTemplate
or ReactiveRedisTemplate
object.
Usage¶
- Add
redisson-spring-data
dependency into your project:
Maven:Gradle:<dependency> <groupId>org.redisson</groupId> <!-- for Spring Data Redis v.1.6.x --> <artifactId>redisson-spring-data-16</artifactId> <!-- for Spring Data Redis v.1.7.x --> <artifactId>redisson-spring-data-17</artifactId> <!-- for Spring Data Redis v.1.8.x --> <artifactId>redisson-spring-data-18</artifactId> <!-- for Spring Data Redis v.2.0.x --> <artifactId>redisson-spring-data-20</artifactId> <!-- for Spring Data Redis v.2.1.x --> <artifactId>redisson-spring-data-21</artifactId> <!-- for Spring Data Redis v.2.2.x --> <artifactId>redisson-spring-data-22</artifactId> <!-- for Spring Data Redis v.2.3.x --> <artifactId>redisson-spring-data-23</artifactId> <!-- for Spring Data Redis v.2.4.x --> <artifactId>redisson-spring-data-24</artifactId> <!-- for Spring Data Redis v.2.5.x --> <artifactId>redisson-spring-data-25</artifactId> <!-- for Spring Data Redis v.2.6.x --> <artifactId>redisson-spring-data-26</artifactId> <!-- for Spring Data Redis v.2.7.x --> <artifactId>redisson-spring-data-27</artifactId> <!-- for Spring Data Redis v.3.0.x --> <artifactId>redisson-spring-data-30</artifactId> <!-- for Spring Data Redis v.3.1.x --> <artifactId>redisson-spring-data-31</artifactId> <!-- for Spring Data Redis v.3.2.x --> <artifactId>redisson-spring-data-32</artifactId> <!-- for Spring Data Redis v.3.3.x --> <artifactId>redisson-spring-data-33</artifactId> <version>3.36.0</version> </dependency>
// for Spring Data Redis v.1.6.x compile 'org.redisson:redisson-spring-data-16:3.36.0' // for Spring Data Redis v.1.7.x compile 'org.redisson:redisson-spring-data-17:3.36.0' // for Spring Data Redis v.1.8.x compile 'org.redisson:redisson-spring-data-18:3.36.0' // for Spring Data Redis v.2.0.x compile 'org.redisson:redisson-spring-data-20:3.36.0' // for Spring Data Redis v.2.1.x compile 'org.redisson:redisson-spring-data-21:3.36.0' // for Spring Data Redis v.2.2.x compile 'org.redisson:redisson-spring-data-22:3.36.0' // for Spring Data Redis v.2.3.x compile 'org.redisson:redisson-spring-data-23:3.36.0' // for Spring Data Redis v.2.4.x compile 'org.redisson:redisson-spring-data-24:3.36.0' // for Spring Data Redis v.2.5.x compile 'org.redisson:redisson-spring-data-25:3.36.0' // for Spring Data Redis v.2.6.x compile 'org.redisson:redisson-spring-data-26:3.36.0' // for Spring Data Redis v.2.7.x compile 'org.redisson:redisson-spring-data-27:3.36.0' // for Spring Data Redis v.3.0.x compile 'org.redisson:redisson-spring-data-30:3.36.0' // for Spring Data Redis v.3.1.x compile 'org.redisson:redisson-spring-data-31:3.36.0' // for Spring Data Redis v.3.2.x compile 'org.redisson:redisson-spring-data-32:3.36.0' // for Spring Data Redis v.3.3.x compile 'org.redisson:redisson-spring-data-33:3.36.0'
- Register
RedissonConnectionFactory
in Spring context:
@Configuration public class RedissonSpringDataConfig { @Bean public RedissonConnectionFactory redissonConnectionFactory(RedissonClient redisson) { return new RedissonConnectionFactory(redisson); } @Bean(destroyMethod = "shutdown") public RedissonClient redisson(@Value("classpath:/redisson.yaml") Resource configFile) throws IOException { Config config = Config.fromYAML(configFile.getInputStream()); return Redisson.create(config); } }
Upgrade to Redisson PRO with advanced features.