CacheConfig
package com.ruijie.returns.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @author YangGang
* @date 2022/7/28
* @description
*/
@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会抛出异常
serializer.setObjectMapper(mapper);
template.setValueSerializer(serializer);
template.setKeySerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
}
@Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory ) {
StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
stringRedisTemplate.setConnectionFactory( redisConnectionFactory );
stringRedisTemplate.setKeySerializer( RedisSerializer.string() );
stringRedisTemplate.setValueSerializer( RedisSerializer.string() );
return stringRedisTemplate;
}
}
RedisUtil
package com.ruijie.returns.config;
import com.ruijie.returns.exception.CacheOptionException;
import com.ruijie.returns.utils.StringConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static com.ruijie.returns.utils.StringConstant.SYSTEM_NAME_LOCK;
/**
* @author YangGang
* @date 2022/7/28
* @description
*/
@Slf4j
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<Object, Object> redisTemplate;
@Autowired
private RedisTemplate<String, ?> redisTemplates;
private static final String PUSH_LIST_TO_CACHE_ERROR_MSG = "将list放入缓存时出错";
/**
* 指定缓存失效时间
*
* @param key 键
* @param time 时间(秒)
* @return
*/
public void expire(String key, long time) throws CacheOptionException {
try {
if (time > 0) {
redisTemplate.expire(StringConstant.SYSTEM_NAME + key, time, TimeUnit.SECONDS);
}
} catch (Exception e) {
throw new CacheOptionException("指定缓存失效时间失败", e);
}
}
/**
* 根据key 获取过期时间
*
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key) {
return redisTemplate.getExpire(StringConstant.SYSTEM_NAME + key, TimeUnit.SECONDS);
}
/**
* 判断key是否存在
*
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key) throws CacheOptionException {
try {
return redisTemplate.hasKey(StringConstant.SYSTEM_NAME + key);
} catch (Exception e) {
throw new CacheOptionException("判断key是否存在失败", e);
}
}
/**
* 删除缓存
*
* @param key 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void del(String... key) throws CacheOptionException {
try {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(StringConstant.SYSTEM_NAME +key[0]);
} else {
List<String> list = (List<String>) CollectionUtils.arrayToList(key);
List<String> newKeys = new ArrayList<>();
for (String newKey : list) {
newKey = StringConstant.SYSTEM_NAME + newKey;
newKeys.add(newKey);
}
redisTemplate.delete(newKeys);
}
}
} catch (Exception e) {
throw new CacheOptionException("删除缓存失败", e);
}
}
/**
* 模糊删除根据前缀key,使用是前缀key必须加*
* @param prefixKey
* @return
*/
public Long delByPrefix(final String prefixKey){
Set<String> keys = redisTemplates.keys(prefixKey);
if(!CollectionUtils.isEmpty(keys)) {
return redisTemplates.delete(keys);
}
return null;
}
/**
* 根据前缀key模糊查询,使用是前缀key必须加*
* @param prefixKey
* @return
*/
public java.util.List<Map<String, Object>> queryByPrefix(final String prefixKey){
Set<String> keys = redisTemplates.keys(prefixKey);
java.util.List<Map<String,Object>> resultList=new ArrayList<Map<String,Object>>();
if(!CollectionUtils.isEmpty(keys)) {
for (String key : keys) {
Map<String, Object> map = new HashMap<String, Object>();
map.put(key, getNative(key));
resultList.add(map);
}
}
return resultList;
}
//============================String=============================
/**
* 普通缓存获取
*
* @param key 键
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(StringConstant.SYSTEM_NAME + key);
}
/**
* 普通缓存获取
*
* @param key 键
* @return 值
*/
public Object getNative(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存放入
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public void set(String key, Object value) throws CacheOptionException {
try {
redisTemplate.opsForValue().set(StringConstant.SYSTEM_NAME + key, value);
} catch (Exception e) {
throw new CacheOptionException("普通缓存放入失败", e);
}
}
/**
* 锁定当前key
* @param key 锁定的key
* @param value 锁定的value
* @param timeout 失效时间
* @param unit
* @return
* @throws CacheOptionException
*/
public boolean lockKey(String key, Object value, long timeout, TimeUnit unit) throws CacheOptionException{
try {
return redisTemplate.opsForValue().setIfAbsent(SYSTEM_NAME_LOCK + key,value,timeout,unit);
} catch (Exception e) {
throw new CacheOptionException("获取锁失败", e);
}
}
/**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public void set(String key, Object value, long time) throws CacheOptionException {
try {
if (time > 0) {
redisTemplate.opsForValue().set(StringConstant.SYSTEM_NAME + key, value, time, TimeUnit.SECONDS);
} else {
set(StringConstant.SYSTEM_NAME + key, value);
}
} catch (Exception e) {
throw new CacheOptionException("普通缓存放入并设置时间失败", e);
}
}
/**
* 递增
*
* @param key 键
* @param delta 要增加几(大于0)
* @return
*/
public long add(String key, long delta) throws CacheOptionException {
if (delta < 0) {
throw new CacheOptionException("保存失败,递增因子必须大于0", null);
}
return redisTemplate.opsForValue().increment(StringConstant.SYSTEM_NAME + key, delta);
}
/**
* 递减
*
* @param key 键
* @param delta 要减少几(小于0)
* @return
*/
public long sub(String key, long delta) throws CacheOptionException {
if (delta < 0) {
throw new CacheOptionException("保存失败,递减因子必须大于0", null);
}
return redisTemplate.opsForValue().increment(StringConstant.SYSTEM_NAME + key, -delta);
}
//================================Map=================================
/**
* HashGet
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object getFromHashMap(String key, String item) {
return redisTemplate.opsForHash().get(StringConstant.SYSTEM_NAME + key, item);
}
/**
* 获取hashKey对应的所有键值
*
* @param key 键
* @return 对应的多个键值
*/
public Map<Object, Object> getMap(String key) {
return redisTemplate.opsForHash().entries(StringConstant.SYSTEM_NAME + key);
}
/**
* set 一个 HashSet
*
* @param key 键
* @param map 对应多个键值
* @return true 成功 false 失败
*/
public void setHashSet(String key, Map<String, Object> map) throws CacheOptionException {
try {
redisTemplate.opsForHash().putAll(StringConstant.SYSTEM_NAME + key, map);
} catch (Exception e) {
throw new CacheOptionException("保存缓存失败", e);
}
}
/**
* HashSet 并设置时间
*
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
* @return true成功 false失败
*/
public void setHashSet(String key, Map<String, Object> map, long time) throws CacheOptionException {
try {
redisTemplate.opsForHash().putAll(StringConstant.SYSTEM_NAME + key, map);
if (time > 0) {
expire(StringConstant.SYSTEM_NAME + key, time);
}
} catch (Exception e) {
throw new CacheOptionException("保存缓存失败", e);
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @return true 成功 false失败
*/
public void setToHashTable(String key, String item, Object value) throws CacheOptionException {
try {
redisTemplate.opsForHash().put(StringConstant.SYSTEM_NAME + key, item, value);
} catch (Exception e) {
throw new CacheOptionException("向一张hash表中放入数据失败", e);
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
public void setToHashTable(String key, String item, Object value, long time) throws CacheOptionException {
try {
redisTemplate.opsForHash().put(StringConstant.SYSTEM_NAME + key, item, value);
if (time > 0) {
expire(StringConstant.SYSTEM_NAME + key, time);
}
} catch (Exception e) {
throw new CacheOptionException("向一张hash表中放入数据失败", e);
}
}
/**
* 删除hash表中的值
*
* @param key 键 不能为null
* @param item 项 可以使多个 不能为null
*/
public void delFormHashTable(String key, Object... item) {
redisTemplate.opsForHash().delete(StringConstant.SYSTEM_NAME + key, item);
}
/**
* 判断hash表中是否有该项的值
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return true 存在 false不存在
*/
public boolean containFromHashTable(String key, String item) {
return redisTemplate.opsForHash().hasKey(StringConstant.SYSTEM_NAME + key, item);
}
/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
*
* @param key 键
* @param item 项
* @param by 要增加几(大于0)
* @return
*/
public double addFromHashTable(String key, String item, double by) throws CacheOptionException {
try {
return redisTemplate.opsForHash().increment(StringConstant.SYSTEM_NAME + key, item, by);
} catch (Exception e) {
throw new CacheOptionException("增加一张hash表中的值失败", e);
}
}
/**
* hash递减
*
* @param key 键
* @param item 项
* @param by 要减少几(小于0)
* @return
*/
public double subFromHashTable(String key, String item, double by) throws CacheOptionException {
try {
return redisTemplate.opsForHash().increment(StringConstant.SYSTEM_NAME + key, item, -by);
} catch (Exception e) {
throw new CacheOptionException("减小一张hash表中的值失败", e);
}
}
//============================set=============================
/**
* 根据 key 获取 Set 集合
*
* @param key 键
* @return
*/
public Set<Object> getFromSetCollection(String key) {
return redisTemplate.opsForSet().members(StringConstant.SYSTEM_NAME + key);
}
/**
* 判断Redis中寸的Set集合中是否存在某元素
*
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public boolean containFromSetCollection(String key, Object value) throws CacheOptionException {
try {
return redisTemplate.opsForSet().isMember(StringConstant.SYSTEM_NAME + key, value);
} catch (Exception e) {
throw new CacheOptionException("判断Redis中寸的Set集合中是否存在某元素", e);
}
}
/**
* 缓存一个Set集合
*
* @param key 键
* @param values 值 可以是多个
* @return 成功个数
*/
public long setSetCollection(String key, Object... values) throws CacheOptionException {
try {
return redisTemplate.opsForSet().add(StringConstant.SYSTEM_NAME + key, values);
} catch (Exception e) {
throw new CacheOptionException("缓存Set集合时出错", e);
}
}
/**
* 将set数据放入缓存
*
* @param key 键
* @param time 时间(秒)
* @param values 值 可以是多个
* @return 成功个数
*/
public long setSetCollection(String key, long time, Object... values) throws CacheOptionException {
try {
Long count = redisTemplate.opsForSet().add(StringConstant.SYSTEM_NAME + key, values);
if (time > 0) {
expire(StringConstant.SYSTEM_NAME + key, time);
}
return count;
} catch (Exception e) {
throw new CacheOptionException("缓存Set集合时出错", e);
}
}
/**
* 获取set缓存的长度
*
* @param key 键
* @return
*/
public long getSetCollectionLength(String key) throws CacheOptionException {
try {
return redisTemplate.opsForSet().size(StringConstant.SYSTEM_NAME + key);
} catch (Exception e) {
throw new CacheOptionException("获取Redis中的Set集合中元素总数出错", e);
}
}
/**
* 从Set集合中删除某个元素
*
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
*/
public long delFromSetCollection(String key, Object... values) throws CacheOptionException {
try {
return redisTemplate.opsForSet().remove(StringConstant.SYSTEM_NAME + key, values);
} catch (Exception e) {
throw new CacheOptionException("从Set集合中删除某个元素时出错", e);
}
}
//===============================list=================================
/**
* 根据位置获取 List 的子列表
*
* @param key 键
* @param start 开始
* @param end 结束 0 到 -1代表所有值
* @return 返回 List 集合指定位置的子列表
*/
public List<Object> getFromListCollection(String key, long start, long end) throws CacheOptionException {
try {
return redisTemplate.opsForList().range(StringConstant.SYSTEM_NAME + key, start, end);
} catch (Exception e) {
throw new CacheOptionException("根据位置获取 List 的子列表时出错", e);
}
}
/**
* 获取list缓存的长度
*
* @param key 键
* @return
*/
public long getListCollectionLength(String key) throws CacheOptionException {
try {
return redisTemplate.opsForList().size(StringConstant.SYSTEM_NAME + key);
} catch (Exception e) {
throw new CacheOptionException("获取list缓存的长度时出错", e);
}
}
/**
* 根据位置获取List中的指定元素
*
* @param key 键
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
* @return
*/
public Object getFromListCollection(String key, long index) throws CacheOptionException {
try {
return redisTemplate.opsForList().index(StringConstant.SYSTEM_NAME + key, index);
} catch (Exception e) {
throw new CacheOptionException("根据位置获取List中的指定元素时出错", e);
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @return
*/
public boolean setListCollection(String key, Object value) throws CacheOptionException {
try {
redisTemplate.opsForList().rightPush(StringConstant.SYSTEM_NAME + key, value);
return true;
} catch (Exception e) {
throw new CacheOptionException(PUSH_LIST_TO_CACHE_ERROR_MSG, e);
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean setListCollection(String key, Object value, long time) throws CacheOptionException {
try {
redisTemplate.opsForList().rightPush(StringConstant.SYSTEM_NAME + key, value);
if (time > 0) {
expire(StringConstant.SYSTEM_NAME + key, time);
}
return true;
} catch (Exception e) {
throw new CacheOptionException(PUSH_LIST_TO_CACHE_ERROR_MSG, e);
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @return
*/
public boolean setListCollection(String key, List<Object> value) throws CacheOptionException {
try {
redisTemplate.opsForList().rightPushAll(StringConstant.SYSTEM_NAME + key, value);
return true;
} catch (Exception e) {
throw new CacheOptionException(PUSH_LIST_TO_CACHE_ERROR_MSG, e);
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean setListCollection(String key, List<Object> value, long time) throws CacheOptionException {
try {
redisTemplate.opsForList().rightPushAll(StringConstant.SYSTEM_NAME + key, value);
if (time > 0) {
expire(StringConstant.SYSTEM_NAME + key, time);
}
return true;
} catch (Exception e) {
throw new CacheOptionException(PUSH_LIST_TO_CACHE_ERROR_MSG, e);
}
}
/**
* 根据索引修改list中的某条数据
*
* @param key 键
* @param index 索引
* @param value 值
* @return
*/
public boolean updateFromListCollection(String key, long index, Object value) throws CacheOptionException {
try {
redisTemplate.opsForList().set(StringConstant.SYSTEM_NAME + key, index, value);
return true;
} catch (Exception e) {
throw new CacheOptionException("根据索引修改list中的某条数据时出错", e);
}
}
/**
* 移除N个值为value
*
* @param key 键
* @param count 移除多少个
* @param value 值
* @return 移除的个数
*/
public long delFromListCollection(String key, long count, Object value) throws CacheOptionException {
try {
return redisTemplate.opsForList().remove(StringConstant.SYSTEM_NAME + key, count, value);
} catch (Exception e) {
throw new CacheOptionException("根据索引修改list中的某条数据时出错", e);
}
}
/**
* 模糊查询获取key值
*
* @param pattern
* @return
*/
public Set getKeys(String pattern) {
return redisTemplate.keys(StringConstant.SYSTEM_NAME + pattern);
}
/**
* 使用Redis的消息队列,发布消息
*
* @param channel
* @param message 消息内容
*/
public void publishMessage(String channel, Object message) {
redisTemplate.convertAndSend(channel, message);
}
/**
* 弹出右边的值 --- 并且移除这个值
*
* @param listKey
*/
public Object boundListOps(String listKey) {
//绑定操作
BoundListOperations<Object, Object> boundValueOperations = redisTemplate.boundListOps(listKey);
return boundValueOperations.rightPop();
}
//=========BoundListOperations 用法 End============
}
单节点配置:
spring.redis.host = k8s-bj-test-nodeports.ruijie.com.cn
spring.redis.port = 32748
spring.redis.password = f773342351564f3aacb242698a9b26e7
spring.redis.lettuce.pool.max-active = 200
spring.redis.lettuce.pool.max-idle = 10
哨兵模式配置:
spring.redis.password = f773342351564f3aacb242698a9b26e7
spring.redis.sentinel.master = mymaster
spring.redis.sentinel.nodes = ces-redis-0d275-0.ces-redis-0d275:26379,ces-redis-0d275-1.ces-redis-0d275:26379,ces-redis-0d275-2.ces-redis-0d275:26379
POM
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.3.0.RELEASE</version>
</dependency>