当前使用RuoYi框架单体服务,配置有默认redis配置使用, 现想新增加另一个redis配置, 并实现保持之前使用的redis不变, 并可以选择性使用不同的redis
当前redis服务配置
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Bean
@SuppressWarnings(value = {"unchecked", "rawtypes"})
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
serializer.setObjectMapper(mapper);
// 使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(serializer);
// Hash的key也采用StringRedisSerializer的序列化方式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(serializer);
template.afterPropertiesSet();
return template;
}
}
当前redis配置默认读取配置文件中的属性,配置redis的连接工厂, 并定义 RedisTemplate Bean,设置了 Redis 的连接工厂以及键和值的序列化方式
新增redis2连接
配置文件增加redis2连接配置
略
配置类代码
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Value("${spring.redis.lettuce.pool.min-idle}")
private int minIdle;
@Value("${spring.redis.lettuce.pool.max-idle}")
private int maxIdle;
@Value("${spring.redis.lettuce.pool.max-active}")
private int maxActive;
@Value("${spring.redis.lettuce.pool.max-wait}")
private long maxWait;
@Value("${spring.redis.lettuce.pool.shutdown-timeout}")
private long shutdownTimeout;
@Value("${spring.redis.host}")
private String redisHost;
@Value("${spring.redis.port}")
private int redisPort;
@Value("${spring.redis.password}")
private String redisPassword;
@Value("${spring.redis.timeout}")
private int redisTimeout;
@Value("${spring.redis.database}")
private int redisDatabase;
@Value("${spring.redis2.host}")
private String redis2Host;
@Value("${spring.redis2.port}")
private int redis2Port;
@Value("${spring.redis2.password}")
private String redis2Password;
@Value("${spring.redis2.timeout}")
private int redis2Timeout;
@Value("${spring.redis2.database}")
private int redis2Database;
@Primary
@Bean("redisConnectionFactory")
public LettuceConnectionFactory redisConnectionFactory() {
GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
genericObjectPoolConfig.setMaxIdle(maxIdle);
genericObjectPoolConfig.setMinIdle(minIdle);
genericObjectPoolConfig.setMaxTotal(maxActive);
genericObjectPoolConfig.setMaxWaitMillis(maxWait);
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
redisStandaloneConfiguration.setDatabase(redisDatabase);
redisStandaloneConfiguration.setHostName(redisHost);
redisStandaloneConfiguration.setPort(redisPort);
redisStandaloneConfiguration.setPassword(RedisPassword.of(redisPassword));
LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
.commandTimeout(Duration.ofMillis(redisTimeout))
.shutdownTimeout(Duration.ofMillis(shutdownTimeout))
.poolConfig(genericObjectPoolConfig)
.build();
return new LettuceConnectionFactory(redisStandaloneConfiguration, clientConfig);
}
@Primary
@Bean("redisTemplate")
@SuppressWarnings(value = {"unchecked", "rawtypes"})
public RedisTemplate<Object, Object> redisTemplate(
@Qualifier("redisConnectionFactory") RedisConnectionFactory connectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL,
JsonTypeInfo.As.PROPERTY);
serializer.setObjectMapper(mapper);
// 使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(serializer);
// Hash的key也采用StringRedisSerializer的序列化方式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(serializer);
template.afterPropertiesSet();
return template;
}
@Primary
@Bean("redisCacheManager")
public RedisCacheManager redisCacheManager(
@Qualifier("redisConnectionFactory") RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
return RedisCacheManager
.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(redisCacheConfiguration).build();
}
@Bean(name = "redisSecondConnectionFactory")
public RedisConnectionFactory redisSecondConnectionFactory() {
GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
genericObjectPoolConfig.setMaxIdle(maxIdle);
genericObjectPoolConfig.setMinIdle(minIdle);
genericObjectPoolConfig.setMaxTotal(maxActive);
genericObjectPoolConfig.setMaxWaitMillis(maxWait);
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
redisStandaloneConfiguration.setDatabase(redis2Database);
redisStandaloneConfiguration.setHostName(redis2Host);
redisStandaloneConfiguration.setPort(redis2Port);
redisStandaloneConfiguration.setPassword(RedisPassword.of(redis2Password));
LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
.commandTimeout(Duration.ofMillis(redis2Timeout))
.shutdownTimeout(Duration.ofMillis(shutdownTimeout))
.poolConfig(genericObjectPoolConfig)
.build();
return new LettuceConnectionFactory(redisStandaloneConfiguration, clientConfig);
}
@Bean(name = "redisSecondTemplate")
@SuppressWarnings(value = {"unchecked", "rawtypes"})
public RedisTemplate<Object, Object> redisSecondTemplate(
@Qualifier("redisSecondConnectionFactory") RedisConnectionFactory redisSecondConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisSecondConnectionFactory);
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer =
new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(jackson2JsonRedisSerializer);
// Hash的key也采用StringRedisSerializer的序列化方式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
@Bean("redisSecondCacheManager")
public RedisCacheManager redisSecondCacheManager(
@Qualifier("redisSecondConnectionFactory") RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofHours(1))// 设置缓存有效期1小时
.computePrefixWith(name -> name + ":");
return RedisCacheManager
.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(redisCacheConfiguration).build();
}
}
将默认读取配置的RedisConnectionFactory使用Bean构建, 并设置@Bean的name区分多个redis的RedisConnectionFactory连接工厂和RedisTemplate获取连接实例的方法及缓存管理RedisCacheManager, 在缓存管理及获取连接实例的方法中使用@Qualifier指定所需要的连接工厂,并将原本redis的Bean方法上添加@Primary注解,表示多个候选 Bean 的时默认选择当前
使用时指定连接实例
在封装类或直接使用时,通过@Qualifier指定所需要获取的实例,
/**
* spring redis 工具类
*
* @author ruoyi
**/
@SuppressWarnings(value = {"unchecked", "rawtypes"})
@Component
public class Redis2Cache{
@Autowired
@Qualifier("redisSecondTemplate")
public RedisTemplate redisTemplate;
/**
* setNx
*
* @param key 缓存的键值
*/
public Boolean setNx3S(final String key) {
Boolean success = redisTemplate.opsForValue().setIfAbsent(key, "123");
boolean locked;
if (success != null && success) {
redisTemplate.expire(key, 3000, TimeUnit.MILLISECONDS);
locked = true;
} else {
locked = false;
}
return locked;
}
}
在@Cacheable的cacheManager 属性中也可以直接设置bean名称来选择redis缓存使用哪个redis连接
@Cacheable(value = “operation:history”, key = “#productCode”, cacheManager = “redisSecondCacheManager”)