若依(RouYi)框架使用多个Redis数据源的方法
application.yml配置
spring:
redis-app:
password: # 密码(默认为空)
timeout: 3000ms # 连接超时时长(毫秒)
cluster:
nodes:
- xx.xx.xx.xx:xx #集群Redis Ip:port
- xx.xx.xx.xx:xx
- xx.xx.xx.xx:xx
- xx.xx.xx.xx:xx
- xx.xx.xx.xx:xx
- xx.xx.xx.xx:xx
- xx.xx.xx.xx:xx
jedis:
pool:
max-active: 1000 # 连接池最大连接数(使用负值表示没有限制)
max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制)
max-idle: 10 # 连接池中的最大空闲连接
min-idle: 5 # 连接池中的最小空闲连接
增加RedisAppUtilString.java
@Component
public class RedisAppUtilString {
@Autowired
@Qualifier("redisConcurrencyTemplate")
private StringRedisTemplate redisTemplate;
public RedisAppUtilString (StringRedisTemplate redisTemplate)
{
this.redisTemplate = redisTemplate;
}
/**
* 指定缓存失效时间
* @param key 键
* @param time 时间(秒)
* @return
*/
public boolean expire(String key,long time){
try {
if(time>0){
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据key 获取过期时间
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key){
return redisTemplate.getExpire(key,TimeUnit.SECONDS);
}
/**
* 判断key是否存在
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key){
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
* @param key 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void del(String ... key){
if(key!=null&&key.length>0){
if(key.length==1){
redisTemplate.delete(key[0]);
}else{
redisTemplate.delete((Collection) CollectionUtils.arrayToList(key));
}
}
}
//============================String=============================
/**
* 普通缓存获取
* @param key 键
* @return 值
*/
public String get(String key){
return key==null?null:redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存放入
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key,String value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key,String value,long time){
try {
if(time>0){
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
}else{
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 递增
* @param key 键
* @param delta 要增加几(大于0)
* @return
*/
public long incr(String key, long delta){
if(delta<0){
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 递减
* @param key 键
* @param delta 要减少几(小于0)
* @return
*/
public long decr(String key, long delta){
if(delta<0){
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
//================================Map=================================
/**
* HashGet
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hget(String key,String item){
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取hashKey对应的所有键值
* @param key 键
* @return 对应的多个键值
*/
public Map
增加RedisAppConfig
@Configuration
@EnableCaching //开启注解
public class RedisAppConfig extends CachingConfigurerSupport {
@Autowired
private Environment environment;
/**
* 配置Redis-App数据源
*
* @return
*/
public RedisConnectionFactory connectionAppFactory(String redisSource) {
RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
String ipPort = environment.getProperty("spring."+redisSource+".cluster.nodes[0]");
Set nodes = new HashSet();
while (ipPort != null) {
String[] ipAndPort = ipPort.split(":");
nodes.add(new RedisNode(ipAndPort[0].trim(), Integer.valueOf(ipAndPort[1])));
ipPort = environment.getProperty("spring."+redisSource+".cluster.nodes["+nodes.size()+"]");
}
redisClusterConfiguration.setPassword(environment.getProperty("spring."+redisSource+".password"));
redisClusterConfiguration.setClusterNodes(nodes);
//RedisClusterConfiguration clusterConfig, JedisPoolConfig poolConfig
//int timeout = Integer.parseInt(environment.getProperty("spring."+redisSource+".timeout"));
int maxIdel = Integer.parseInt(environment.getProperty("spring."+redisSource+".jedis.pool.max-idle"));
int minIdel = Integer.parseInt(environment.getProperty("spring."+redisSource+".jedis.pool.min-idle"));
int maxActive = Integer.parseInt(environment.getProperty("spring."+redisSource+".jedis.pool.max-active"));
//int maxWait = Integer.parseInt(environment.getProperty("spring."+redisSource+".jedis.pool.max-wait"));
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxIdle(maxIdel);
poolConfig.setMinIdle(minIdel);
poolConfig.setMaxTotal(maxActive);
//genericObjectPoolConfig.setMaxWaitMillis(maxWait);
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisClusterConfiguration,poolConfig);
jedisConnectionFactory.afterPropertiesSet();
return jedisConnectionFactory;
}
/**
* 配置第一个数据源的连接工厂
* 这里注意:需要添加@Primary 指定bean的名称,目的是为了创建两个不同名称的LettuceConnectionFactory
*
* @return
*/
@Bean("dataFactory")
@Primary
public RedisConnectionFactory dataFactory() {
return connectionAppFactory("redis");
}
//第二个数据源的连接工厂
@Bean("concurrencyFactory")
public RedisConnectionFactory concurrencyFactory() {
return connectionAppFactory("redis-app");
}
/**
* 配置第一个数据源的RedisTemplate
* 注意:这里指定使用名称=factory 的 RedisConnectionFactory
* 并且标识第一个数据源是默认数据源 @Primary
*
* @param dataFactory
* @return
*/
@Bean("redisDataTemplate")
@Primary
public StringRedisTemplate redisDataTemplate(@Qualifier("dataFactory") RedisConnectionFactory dataFactory) {
return getRedisDataTemplate(dataFactory);
}
//第二个数据源
@Bean("redisConcurrencyTemplate")
public StringRedisTemplate redisConcurrencyTemplate(@Qualifier("concurrencyFactory") RedisConnectionFactory concurrencyFactory) {
return getRedisConcurrencyTemplate(concurrencyFactory);
}
/**
* 设置序列化方式 (这一步不是必须的)
*
* @return
*/
private StringRedisTemplate getRedisDataTemplate(RedisConnectionFactory factory) {
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(factory);
//redis 的key 不带""号,如key
template.setKeySerializer(new StringRedisSerializer());
//redis 的value 不带""号,如value
template.setValueSerializer(new StringRedisSerializer());
template.setHashKeySerializer(stringRedisSerializer);
template.setHashValueSerializer(stringRedisSerializer);
template.afterPropertiesSet();
return template;
}
@Bean
public StringRedisTemplate getRedisConcurrencyTemplate(RedisConnectionFactory factory) {
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(factory);
//redis 的key 不带""号,如key
template.setKeySerializer(new StringRedisSerializer());
//redis 的value 不带""号,如value
template.setValueSerializer(new StringRedisSerializer());
template.setHashKeySerializer(stringRedisSerializer);
template.setHashValueSerializer(stringRedisSerializer);
template.afterPropertiesSet();
return template;
}
/**
* 对hash类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public HashOperations hashOperations(RedisTemplate redisTemplate) {
return redisTemplate.opsForHash();
}
/**
* 对redis字符串类型数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public ValueOperations valueOperations(RedisTemplate redisTemplate) {
return redisTemplate.opsForValue();
}
/**
* 对链表类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public ListOperations listOperations(RedisTemplate redisTemplate) {
return redisTemplate.opsForList();
}
/**
* 对无序集合类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public SetOperations setOperations(RedisTemplate redisTemplate) {
return redisTemplate.opsForSet();
}
/**
* 对有序集合类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public ZSetOperations zSetOperations(RedisTemplate redisTemplate) {
return redisTemplate.opsForZSet();
}
}
使用示例
@Autowired
private RedisAppUtilString redisUtilString;
...
String redisValue = redisUtilString.hget(key,item).toString();