SpringBoot 集成 Redis
SpringBoot 2.3.1
Redis 更多实操 记录 (https://github.com/yanghaiji/Advanced-books/blob/master/note/redis/README.md
添加依赖
这里我们采用的是 lettuce
所以必须引入commons-pool2
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
配置文件
spring:
redis:
host: 127.0.0.1
port: 6379
database: 0
# password:
timeout: 6000
# 链接池
lettuce:
pool:
max-active: 10
max-idle: 10
max-wait: 0
自定义 RedisConfiguration
public class RedisConfiguration {
private final LettuceConnectionFactory lettuceConnectionFactory;
public RedisConfiguration(LettuceConnectionFactory lettuceConnectionFactory) {
this.lettuceConnectionFactory = lettuceConnectionFactory;
}
@Bean("redisTemplate")
@ConditionalOnProperty(name = "spring.redis.host", matchIfMissing = true)
public RedisTemplate<String, Object> getSingleRedisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
RedisSerializer redisObjectSerializer = new RedisObjectSerializer();
redisTemplate.setConnectionFactory(lettuceConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(redisObjectSerializer);
redisTemplate.setHashValueSerializer(redisObjectSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean
public HashOperations<String, String, String> hashOperations(StringRedisTemplate stringRedisTemplate) {
return stringRedisTemplate.opsForHash();
}
@Bean
public ListOperations<String,Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForList();
}
@Bean
public ZSetOperations<String,Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForZSet();
}
@Bean
public SetOperations<String,Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForSet();
}
@Bean
public ValueOperations<String,Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForValue();
}
/**
* redis工具类
*/
@Bean("redisUtil")
public RedisUtil redisUtil(RedisTemplate<String, Object> redisTemplate,
StringRedisTemplate stringRedisTemplate,
HashOperations<String, String, String> hashOperations,
ListOperations<String,Object> listOperations,
ZSetOperations<String,Object>zSetOperations,
SetOperations<String,Object> setOperations,
ValueOperations<String,Object> valueOperations) {
return new RedisUtil(redisTemplate, stringRedisTemplate,hashOperations,listOperations,
zSetOperations,setOperations,valueOperations);
}
}
自定义 RedisUtil
这里只截取了一部分,更多的源码请移步source-code 内的redis 目录
@Slf4j
public class RedisUtil<K,V> implements RedisServer<K,V>{
private RedisTemplate<K, V> redisTemplate;
private StringRedisTemplate stringRedisTemplate;
private HashOperations<K, K, V> hashOperations;
private ListOperations<K,V> listOperations;
private ZSetOperations<K,V> zSetOperations;
private SetOperations<K,V> setOperations;
private ValueOperations<K,V> valueOperations;
public RedisUtil(RedisTemplate<K, V> redisTemplate,
StringRedisTemplate stringRedisTemplate,
HashOperations<K, K, V> hashOperations,
ListOperations<K, V> listOperations,
ZSetOperations<K, V> zSetOperations,
SetOperations<K, V> setOperations,
ValueOperations<K,V> valueOperations) {
this.redisTemplate = redisTemplate;
this.stringRedisTemplate = stringRedisTemplate;
this.hashOperations = hashOperations;
this.listOperations = listOperations;
this.zSetOperations = zSetOperations;
this.setOperations = setOperations;
this.valueOperations = valueOperations;
}
/**
* 指定缓存失效时间
*
* @param key 键
* @param time 时间(秒)
* @return
*/
@Override
public boolean expire(K key, long time) {
checkKey(key);
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代表为永久有效
*/
@Override
public long getExpire(K key) {
checkKey(key);
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 判断key是否存在
*
* @param key 键
* @return true 存在 false不存在
*/
@Override
public boolean hasKey(K key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
*
* @param key 可以传一个值 或多个
*/
@Override
@SuppressWarnings("unchecked")
public void del(K... key) {
checkKey(key);
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
// ============================String=============================
/**
* 普通缓存获取
*
* @param key 键
* @return 值
*/
@Override
public V get(K key) {
checkKey(key);
return key == null ? null :valueOperations.get(key);
}
/**
* 普通缓存放入
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
@Override
public boolean set(K key, V value) {
checkKey(key);
try {
valueOperations.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 失败
*/
@Override
public boolean set(K key, V value, long time) {
checkKey(key);
try {
if (time > 0) {
valueOperations.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
*/
@Override
public long incr(K key, long delta) {
checkKey(key);
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return valueOperations.increment(key, delta);
}
/**
* 递减
*
* @param key 键
* @param delta 要减少几(小于0)
* @return
*/
@Override
public long decr(K key, long delta) {
checkKey(key);
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return valueOperations.increment(key, -delta);
}
// ================================Map=================================
/**
* HashGet
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
@Override
public V hget(K key, K item) {
checkKey(key);
return hashOperations.get(key, item);
}
/**
* 获取hashKey对应的所有键值
*
* @param key 键
* @return 对应的多个键值
*/
@Override
public Map<K,V> hmget(K key) {
checkKey(key);
return hashOperations.entries(key);
}
/**
* HashSet
*
* @param key 键
* @param map 对应多个键值
* @return true 成功 false 失败
*/
@Override
public boolean hmset(K key, Map<K, V> map) {
checkKey(key);
try {
hashOperations.putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* HashSet 并设置时间
*
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
* @return true成功 false失败
*/
@Override
public boolean hmset(K key, Map<K, V> map, long time) {
checkKey(key);
try {
hashOperations.putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @return true 成功 false失败
*/
@Override
public boolean hset(K key, K item, V value) {
checkKey(key);
try {
hashOperations.put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
@Override
public boolean hset(K key, K item, V value, long time) {
checkKey(key);
try {
hashOperations.put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除hash表中的值
*
* @param key 键 不能为null
* @param item 项 可以使多个 不能为null
*/
@Override
public void hdel(K key, V... item) {
checkKey(key);
hashOperations.delete(key, item);
}
/**
* 判断hash表中是否有该项的值
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return true 存在 false不存在
*/
@Override
public boolean hHasKey(K key, K item) {
checkKey(key);
return hashOperations.hasKey(key, item);
}
/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
*
* @param key 键
* @param item 项
* @param by 要增加几(大于0)
* @return
*/
@Override
public double hincr(K key, K item, double by) {
checkKey(key);
return hashOperations.increment(key, item, by);
}
/**
* hash递减
*
* @param key 键
* @param item 项
* @param by 要减少记(小于0)
* @return
*/
@Override
public double hdecr(K key, K item, double by) {
checkKey(key);
return hashOperations.increment(key, item, -by);
}
// ============================set=============================
/**
* 根据key获取Set中的所有值
*
* @param key 键
* @return
*/
@Override
public Set<V> sGet(K key) {
checkKey(key);
try {
return setOperations.members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 根据value从一个set中查询,是否存在
*
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
@Override
public boolean sHasKey(K key, V value) {
checkKey(key);
try {
return setOperations.isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将数据放入set缓存
*
* @param key 键
* @param values 值 可以是多个
* @return 成功个数
*/
@Override
public long sSet(K key, V... values) {
checkKey(key);
try {
return setOperations.add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 将set数据放入缓存
*
* @param key 键
* @param time 时间(秒)
* @param values 值 可以是多个
* @return 成功个数
*/
@Override
public long sSetAndTime(K key, long time, V... values) {
checkKey(key);
try {
Long count = setOperations.add(key, values);
if (time > 0) {
expire(key, time);
}
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 获取set缓存的长度
*
* @param key 键
* @return
*/
@Override
public long sGetSetSize(K key) {
checkKey(key);
try {
return setOperations.size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 移除值为value的
*
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
*/
@Override
public long setRemove(K key, V... values) {
checkKey(key);
try {
Long count = setOperations.remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
// ===============================list=================================
/**
* 获取list缓存的内容
*
* @param key 键
* @param start 开始
* @param end 结束 0 到 -1代表所有值
* @return
*/
@Override
public List<V> lGet(K key, long start, long end) {
checkKey(key);
try {
return listOperations.range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取list缓存的长度
*
* @param key 键
* @return
*/
@Override
public long lGetListSize(K key) {
checkKey(key);
try {
return listOperations.size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 通过索引 获取list中的值
*
* @param key 键
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
* @return
*/
@Override
public V lGetIndex(K key, long index) {
checkKey(key);
try {
return listOperations.index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @return
*/
@Override
public boolean lSet(K key, V value) {
checkKey(key);
try {
listOperations.rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
@Override
public boolean lSet(K key, V value, long time) {
checkKey(key);
try {
listOperations.rightPush(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @return
*/
@Override
public boolean lSet(K key, List<V> value) {
checkKey(key);
try {
listOperations.rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
@Override
public boolean lSet(K key, List<V> value, long time) {
checkKey(key);
try {
listOperations.rightPushAll(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据索引修改list中的某条数据
*
* @param key 键
* @param index 索引
* @param value 值
* @return
*/
@Override
public boolean lUpdateIndex(K key, long index, V value) {
checkKey(key);
try {
listOperations.set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 移除N个值为value
*
* @param key 键
* @param count 移除多少个
* @param value 值
* @return 移除的个数
*/
@Override
public long lRemove(K key, long count, V value) {
checkKey(key);
try {
Long remove = listOperations.remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 模糊查询获取key值
*
* @param pattern
* @return
*/
@Override
public Set<K> keys(K pattern) {
checkKey(pattern);
return redisTemplate.keys(pattern);
}
/**
* 使用Redis的消息队列
*
* @param channel
* @param message 消息内容
*/
@Override
public void convertAndSend(K channel, V message) {
redisTemplate.convertAndSend(String.valueOf(channel), message);
}
// =========BoundListOperations 用法 start============
/**
* 将数据添加到Redis的list中(从右边添加)
*
* @param listKey
* @param expireEnum 有效期的枚举类
* @param values 待添加的数据
*/
@Override
public void addToListRight(K listKey, Status.ExpireEnum expireEnum, V... values) {
// 绑定操作
BoundListOperations<K, V> boundValueOperations = redisTemplate.boundListOps(listKey);
// 插入数据
boundValueOperations.rightPushAll(values);
// 设置过期时间
boundValueOperations.expire(expireEnum.getTime(), expireEnum.getTimeUnit());
}
/**
* 根据起始结束序号遍历Redis中的list
*
* @param listKey
* @param start 起始序号
* @param end 结束序号
* @return
*/
@Override
public List<V> rangeList(K listKey, long start, long end) {
// 绑定操作
BoundListOperations<K, V> boundValueOperations = redisTemplate.boundListOps(listKey);
// 查询数据
return boundValueOperations.range(start, end);
}
/**
* 弹出右边的值 --- 并且移除这个值
*
* @param listKey
*/
@Override
public V rifhtPop(K listKey) {
// 绑定操作
BoundListOperations<K, V> boundValueOperations = redisTemplate.boundListOps(listKey);
return boundValueOperations.rightPop();
}
private static long getTime() {
return (long) ((Math.random() * 200) + 1);
}
/**
* <p>
* 获取随机数
* </p>
* @version 1.0.0
* @author Dylan-haiji
* @since 2020/3/5
* @param num
* @return long
*/
private static long getTime(long num) {
if (num == 0) {
num = getTime();
}
num <<= 2;
return num;
}
@SafeVarargs
private void checkKey(K... key){
if(Objects.isNull(key)){
throw new RedisKeyException("Redis key is null");
}
}
}
测试
@RestController
@RequestMapping(value = "/redis/")
public class RedisApiWeb {
@Autowired
private RedisUtil redisUtil;
@GetMapping("test")
public void redisTest(){
redisUtil.set("redis","Hello World");
System.out.println(redisUtil.get("redis"));
Map<String,Object> map = new HashMap<>();
map.put("hash01","hash02");
redisUtil.hmset("myHash",map,100);
System.out.println(redisUtil.hmget("myHash"));
}
}