【redis系列】redisTemplate缓存常用工具类

背景

日常开发过程中,大家使用redis缓存基本上是家常便饭,但是代码中使用redisTemplate组件会略显得麻烦,使用时需要开发人员查阅官网文档,具体场景使用哪些方法,会花费相对的时间,故小编为提升开发效率,整理一些基本常用的交互缓存的方法,涉及redis相关的数据结构:String,List,Set,ZSet,应对大家日常开发足以。
如果该类中缺失常用的方法,希望小伙伴们评论区留言,及时更新!!!

工具类

package com.anhuanjia.ehs.ahj.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.RedisClusterNode;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisServerCommands;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author wx
 * @date 2021/12/7 8:44 下午
 * @describe redis工具类
 */
@Slf4j
public class RedisUtil {
	@Resource
	private RedisTemplate<String, Object> redisTemplate;


	public RedisUtil(RedisTemplate<String, Object> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

	/**
	 * 获取链接工厂
	 */
	public RedisConnectionFactory getConnectionFactory() {
		return this.redisTemplate.getConnectionFactory();
	}

	/**
	 * 获取 RedisTemplate对象
	 */
	public RedisTemplate<String, Object> getRedisTemplate() {
		return redisTemplate;
	}


	/**
	 * 清空DB
	 *
	 * @param node redis 节点
	 */
	public void flushDB(RedisClusterNode node) {
		this.redisTemplate.opsForCluster().flushDb(node);
	}

	/**
	 * 获取指定key的过期时间
	 *
	 * @param key 缓存key
	 */
	public Long getExpire(final String key) {
		return this.redisTemplate.getExpire(key);
	}

	/**
	 * 添加到带有 过期时间的  缓存
	 *
	 * @param key      redis主键
	 * @param value    值
	 * @param time     过期时间
	 * @param timeUnit 过期时间单位
	 */
	public void setExpire(final String key, final Object value, final long time, final TimeUnit timeUnit) {
		redisTemplate.opsForValue().set(key, value, time, timeUnit);
	}

	/**
	 * 添加 缓存、值并设置过期时间,默认过期单位,秒
	 *
	 * @param key
	 * @param value
	 * @param time
	 */
	public void setExpire(final String key, final Object value, final long time) {
		this.setExpire(key, value, time, TimeUnit.SECONDS);
	}

	/**
	 * 单独给某个key设置过期时间(缓存中已存在的key)
	 *
	 * @param key
	 * @param time
	 * @param timeUnit
	 */
	public void expire(final String key, final long time, final TimeUnit timeUnit) {
		redisTemplate.expire(key, time, timeUnit);
	}

	/**
	 * 一次性添加数组到   过期时间的  缓存,不用多次连接,节省开销
	 *
	 * @param keys   the keys
	 * @param values the values
	 */
	public void setKeys(final String[] keys, final Object[] values) {
		//key和value数组之间索引对应
		for (int i = 0; i < keys.length; i++) {
			redisTemplate.opsForValue().set(keys[i], values[i]);
		}
	}


	/**
	 * 添加到缓存key-value格式
	 *
	 * @param key   the key
	 * @param value the value
	 */
	public void setKey(final String key, final Object value) {
		redisTemplate.opsForValue().set(key, value);
	}


	/**
	 * 模糊获取keyPatten的所有  key
	 *
	 * @param keyPatten the key patten
	 * @return the set
	 */
	public Set<String> getKeys(final String keyPatten) {
		return redisTemplate.keys(keyPatten + "*");
	}

	/**
	 * 根据key获取对象value
	 *
	 * @param key the key
	 * @return the string
	 */
	public Object getValue(final String key) {
		return redisTemplate.opsForValue().get(key);
	}

	/**
	 * 获取指定key原来的value并重新赋值
	 *
	 * @param key
	 * @param newValue 新value
	 * @return 旧的value
	 */
	public Object getAndSet(final String key, final Object newValue) {
		return redisTemplate.opsForValue().getAndSet(key, newValue);
	}

	/**
	 * 根据keyList获取所有key的value对象
	 *
	 * @param keyList 集合key
	 * @return
	 */
	public List<Object> multiGet(List<String> keyList) {
		return redisTemplate.opsForValue().multiGet(keyList);
	}


	/**
	 * 针对hashMap数据结构的相关操作
	 *
	 * @return the hash operations
	 */
	public HashOperations<String, String, Object> opsForHash() {
		return redisTemplate.opsForHash();
	}

	/**
	 * 对HashMap操作
	 *
	 * @param key       缓存redis中的key
	 * @param hashKey   Map<key,value>数据结构中的key
	 * @param hashValue Map<key,value>数据结构中的value
	 */
	public void putHashValue(String key, String hashKey, Object hashValue) {
		this.opsForHash().put(key, hashKey, hashValue);
	}


	/**
	 * 获取hashMap结构中指定hashKey对应的hashValue值
	 *
	 * @param key     缓存的key
	 * @param hashKey Map<key,value>数据结构中的key
	 * @return the hash values
	 */
	public Object getHashValues(String key, String hashKey) {
		return opsForHash().get(key, hashKey);
	}

	/**
	 * 删除指定key中hashMap中的若干元素
	 *
	 * @param key      the key
	 * @param hashKeys the hash keys
	 */
	public void delHashValues(String key, Object... hashKeys) {
		this.opsForHash().delete(key, hashKeys);
	}

	/**
	 * 获取指定key的hashMap数据元素
	 *
	 * @param key the key
	 * @return the hash value
	 */
	public Map<String, Object> getHashValue(String key) {
		return this.opsForHash().entries(key);
	}


	/**
	 * 批量添加hashMap数据元素
	 *
	 * @param key the key
	 * @param map the map
	 */
	public void putHashValues(String key, Map<String, Object> map) {
		opsForHash().putAll(key, map);
	}


	/**
	 * 集合数量
	 *
	 * @return the long
	 */
	public long dbSize() {
		return redisTemplate.execute(RedisServerCommands::dbSize);
	}

	/**
	 * 清空redis存储的数据
	 *
	 * @return the string
	 */
	public String flushDB() {
		return redisTemplate.execute((RedisCallback<String>) connection -> {
			connection.flushDb();
			return "ok";
		});
	}

	/**
	 * 判断某个主键是否存在
	 *
	 * @param key the key
	 * @return the boolean
	 */
	public boolean exists(final String key) {
		return this.redisTemplate.hasKey(key);
	}


	/**
	 * 删除key
	 *
	 * @param keys the keys
	 * @return the long
	 */
	public boolean del(final String... keys) {
		boolean result = false;
		for (String key : keys) {
			result = redisTemplate.delete(key);
		}
		return result;
	}

	/**
	 * 对某个主键对应的值加一,value值必须是全数字的字符串
	 *
	 * @param key the key
	 * @return the long
	 */
	public long incrValue(final String key, final long addValue) {
		return redisTemplate.opsForValue().increment(key, addValue);
	}


	/**
	 * 对某个主键对应的值减一,value值必须是全数字的字符串
	 *
	 * @param key the key
	 * @return the long
	 */
	public long decrValue(final String key) {
		return redisTemplate.opsForValue().decrement(key);
	}


	/**
	 * List数据结构相关操作
	 *
	 * @return the list operations
	 */
	public ListOperations<String, Object> opsForList() {
		return redisTemplate.opsForList();
	}

	/**
	 * redis List数据结构 : 将一个或多个值 value 插入到列表 key 的表头
	 *
	 * @param key   the key
	 * @param value the value
	 * @return the long
	 */
	public Long leftPush(String key, Object value) {
		return opsForList().leftPush(key, value);
	}

	/**
	 * redis List数据结构 : 移除并返回列表 key 的头元素
	 *
	 * @param key the key
	 * @return the string
	 */
	public Object leftPop(String key) {
		return opsForList().leftPop(key);
	}

	/**
	 * redis List数据结构 :将一个或多个值 value 插入到列表 key 的表尾(最右边)。
	 *
	 * @param key   the key
	 * @param value the value
	 * @return the long
	 */
	public Long rightPush(String key, Object value) {
		return opsForList().rightPush(key, value);
	}

	/**
	 * redis List数据结构 : 移除并返回列表 key 的末尾元素
	 *
	 * @param key the key
	 * @return the string
	 */
	public Object rightPop(String key) {
		return opsForList().rightPop(key);
	}

	/**
	 * redis List数据结构 : 返回列表 key 的长度 ;
	 * 如果 key 不存在,则 key 被解释为一个空列表,返回 0 ;
	 * 如果 key 不是列表类型,返回一个错误。
	 *
	 * @param key the key
	 * @return the long
	 */
	public Long listLength(String key) {
		return opsForList().size(key);
	}

	/**
	 * redis List数据结构:移除指定个数count的value
	 *
	 * @param key   要移除元素的key
	 * @param count 移除个数,count==0,移除list中所有指定value的元素;
	 *              count<0,从表尾向表头移动,移除count绝对值的value元素;
	 *              count>0 ,从表头向表尾移动,移除count的value元素;
	 * @param value 移除的value
	 * @return
	 */
	public Long removeListValues(String key, Long count, Object value) {
		return this.opsForList().remove(key, count, value);
	}

	/**
	 * redis List数据结构 : 将列表 key 下标为 index 的元素的值设置为 value
	 *
	 * @param key   the key
	 * @param index the index
	 * @param value the value
	 */
	public void listSetValue(String key, long index, Object value) {
		opsForList().set(key, index, value);
	}

	/**
	 * redis List数据结构 : 返回列表 key 中指定区间内的元素,区间以偏移量 start 和 end 指定。
	 *
	 * @param key   the key
	 * @param start the start
	 * @param end   the end
	 * @return the list
	 */
	public List<Object> getList(String key, int start, int end) {
		return opsForList().range(key, start, end);
	}

	/**
	 * redis List数据结构 : 返回列表 key 中指定区间内的元素,区间以偏移量 start 和 end 指定。
	 *
	 * @param key             the key
	 * @param start           the start
	 * @param end             the end
	 * @param valueSerializer 序列化
	 * @return the list
	 */
	public List<Object> getList(String key, int start, int end, RedisSerializer<Object> valueSerializer) {
		byte[] rawKey = rawKey(key);
		return redisTemplate.execute(connection -> deserializeValues(connection.lRange(rawKey, start, end), valueSerializer), true);
	}


	/**
	 * redis List数据结构 : 批量存储
	 *
	 * @param key  the key
	 * @param list the list
	 * @return the long
	 */
	public Long leftPushAll(String key, Object[] list) {
		return opsForList().leftPushAll(key, list);
	}

	/**
	 * redis List数据结构 : 将值 value 插入到列表 key 当中,位于值 index之后。
	 *
	 * @param key   the key
	 * @param index the index
	 * @param value the value
	 */
	public void listInsertValue(String key, long index, Object value) {
		opsForList().set(key, index, value);
	}

	/**
	 * Set数据结构相关操作
	 *
	 * @return SetOperations
	 */
	public SetOperations<String, Object> opsForSet() {
		return redisTemplate.opsForSet();
	}

	/**
	 * 存储set集合类型数据
	 *
	 * @param key   key值
	 * @param value value对象
	 */
	public void setAdd(String key, Object... value) {
		this.opsForSet().add(key, value);
	}

	/**
	 * 随机获取set集合中元素
	 *
	 * @param key key值
	 * @return
	 */
	public Object randomSetMember(String key) {
		return this.opsForSet().randomMember(key);
	}


	/**
	 * 获取set集合
	 *
	 * @param key
	 * @return
	 */
	public Set<Object> getSetMember(String key) {
		return this.opsForSet().members(key);
	}

	/**
	 * 移除指定set集合中的元素
	 *
	 * @param key   集合key
	 * @param value 移除元素
	 */
	public void removeSetMember(String key, Object... value) {
		redisTemplate.opsForSet().remove(key, value);
	}

	/**
	 * 获取set集合的大小
	 *
	 * @param key
	 * @return
	 */
	public Long getSetSize(String key) {
		return redisTemplate.opsForSet().size(key);
	}

	/**
	 * set里面是否包含成员
	 *
	 * @param key
	 * @param value
	 * @return
	 */
	public Boolean isSetMember(String key, Object value) {
		return redisTemplate.opsForSet().isMember(key, value);
	}

	/**
	 * ZSet数据结构相关操作
	 *
	 * @return ZSetOperations
	 */
	public ZSetOperations<String, Object> opsForZSet() {
		return redisTemplate.opsForZSet();
	}


	/**
	 * redis zSet 添加元素
	 *
	 * @param key
	 * @param value
	 * @param score
	 */
	public Boolean zSetAdd(String key, Object value, double score) {
		return opsForZSet().add(key, value, score);
	}

	/**
	 * 根据Score的范围查找值
	 *
	 * @param key
	 * @param min
	 * @param max
	 * @return
	 */
	public Set<Object> zSetRangeByScore(String key, double min, double max) {
		return opsForZSet().rangeByScore(key, min, max);
	}

	/**
	 * 根据Score的范围删除值
	 *
	 * @param key
	 * @param min
	 * @param max
	 */
	public void zSetRemRangeByScore(String key, double min, double max) {
		opsForZSet().removeRangeByScore(key, min, max);
	}

	/**
	 * 升序删除一定范围的值
	 *
	 * @param key
	 * @param start
	 * @param end
	 */
	public void zSetRemoveRange(String key, Long start, Long end) {
		opsForZSet().removeRange(key, start, end);
	}

	/**
	 * 批量移除
	 *
	 * @param key
	 * @param values
	 */
	public void zSetRemove(String key, Object... values) {
		opsForZSet().remove(key, values);
	}

	/**
	 * 根据key获取zSet的数量
	 *
	 * @param key
	 */
	public Long zSetCard(String key) {
		return opsForZSet().zCard(key);
	}

	/**
	 * 根据score倒序范围排列, start, end为偏移量,开始位移和结束位移
	 *
	 * @param key
	 * @param start
	 * @param end
	 * @return
	 */
	public Set<Object> zSetReverseRange(String key, Long start, Long end) {
		return opsForZSet().reverseRange(key, start, end);
	}

	/**
	 * 根据Score升序范围排列, start, end为偏移量,开始位移和结束位移
	 *
	 * @param key
	 * @param start
	 * @param end
	 * @return
	 */
	public Set<Object> zSetRange(String key, Long start, Long end) {
		return opsForZSet().range(key, start, end);
	}

	/**
	 * 修改单个score的值,策略:先删除该score,然后新加该值
	 *
	 * @param key
	 * @param score
	 */
	public void zSetModifyScoreSet(String key, Double score, Object value) {
		this.zSetRemRangeByScore(key, score, score);
		this.zSetAdd(key, value, score);
	}

	/**
	 * 判断zSet中是否有值
	 *
	 * @param key
	 * @param value
	 * @return
	 */
	public Boolean zSetIsMember(String key, Object value) {
		Long rank = opsForZSet().rank(key, value);
		return rank != null;
	}

	/**
	 * 获取某个值对应的score
	 *
	 * @param key
	 * @param value
	 * @return
	 */
	public Double zSetScore(String key, Object value) {
		return opsForZSet().score(key, value);
	}

	private byte[] rawKey(Object key) {

		if (key instanceof byte[]) {
			return (byte[]) key;
		}
		RedisSerializer<Object> redisSerializer = (RedisSerializer<Object>) redisTemplate.getKeySerializer();
		return redisSerializer.serialize(key);
	}

	private byte[] rawValue(Object value, RedisSerializer valueSerializer) {
		if (value instanceof byte[]) {
			return (byte[]) value;
		}

		return valueSerializer.serialize(value);
	}

	private List deserializeValues(List<byte[]> rawValues, RedisSerializer<Object> valueSerializer) {
		if (valueSerializer == null) {
			return rawValues;
		}
		return SerializationUtils.deserialize(rawValues, valueSerializer);
	}

	private Object deserializeValue(byte[] value, RedisSerializer<Object> valueSerializer) {
		if (valueSerializer == null) {
			return value;
		}
		return valueSerializer.deserialize(value);
	}
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

溪~源

你的鼓励将是我源源不断的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值