在Spring Boot中配置Redis多數據源并設置過期時間,你需要遵循以下步驟:
確保你的pom.xml
文件中包含了Spring Boot Redis的依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
在application.yml
或application.properties
文件中配置多個數據源。例如:
# application.yml
spring:
redis:
datasource1:
host: localhost
port: 6379
password: your_password
database: 0
timeout: 60000
datasource2:
host: localhost
port: 6380
password: your_password
database: 1
timeout: 60000
創建一個配置類,用于創建和配置多個Redis數據源。例如:
@Configuration
public class RedisDataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.redis.datasource1")
public DataSource redisDataSource1() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix = "spring.redis.datasource2")
public DataSource redisDataSource2() {
return DataSourceBuilder.create().build();
}
@Bean
public RedisTemplate<String, Object> redisTemplate1(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
return template;
}
@Bean
public RedisTemplate<String, Object> redisTemplate2(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
return template;
}
}
創建一個配置類,用于配置多個數據源的RedisTemplate
。例如:
@Configuration
public class RedisConfig {
@Autowired
private RedisDataSourceConfig redisDataSourceConfig;
@Bean
public RedisTemplate<String, Object> redisTemplate1() {
RedisTemplate<String, Object> template = redisDataSourceConfig.redisTemplate1(redisDataSourceConfig.redisDataSource1());
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.afterPropertiesSet();
return template;
}
@Bean
public RedisTemplate<String, Object> redisTemplate2() {
RedisTemplate<String, Object> template = redisDataSourceConfig.redisTemplate2(redisDataSourceConfig.redisDataSource2());
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
在你的服務類中,使用RedisTemplate
設置過期時間。例如:
@Service
public class MyService {
@Autowired
private RedisTemplate<String, Object> redisTemplate1;
public void setKeyWithExpiration(String key, Object value, int expiration) {
redisTemplate1.opsForValue().set(key, value, expiration, TimeUnit.SECONDS);
}
}
在這個例子中,我們為第一個數據源設置了過期時間為expiration
秒。你可以根據需要調整數據源和過期時間。