在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
秒。你可以根据需要调整数据源和过期时间。