RedisTemplate操作redis方法封装

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
 * 创 建 人 : wangsheng 创建日期:2020年3月
 */
@Component
public class RedisUtils {
    private RedisUtils() {
    }

    @Resource
    private RedisTemplate<String, Object> redisTemplate ;

    /**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @return true=设置成功;false=设置失败
     */
    public  boolean expire(final String key, final long timeout) {

        return expire(key, timeout, TimeUnit.SECONDS);
    }

    /**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @param unit 时间单位
     * @return true=设置成功;false=设置失败
     */
    public  boolean expire(final String key, final long timeout, final TimeUnit unit) {

        Boolean ret = redisTemplate.expire(key, timeout, unit);
        return ret != null && ret;
    }

    /**
     * 删除单个key
     *
     * @param key 键
     * @return true=删除成功;false=删除失败
     */
    public  boolean delKey(final String key) {

        Boolean ret = redisTemplate.delete(key);
        return ret != null && ret;
    }

    /**
     * 删除多个key
     *
     * @param keys 键集合
     * @return 成功删除的个数
     */
    public  long delKeys(final Collection<String> keys) {

        Long ret = redisTemplate.delete(keys);
        return ret == null ? 0 : ret;
    }

    /**
     * 存入key-value普通对象
     * @param key Redis键
     * @param value 值
     */
    public  void setValue(final String key, final Object value) {

        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 存入key-value普通对象
     *
     * @param key Redis键
     * @param value 值
     * @param timeout 时间
     *  @param timeout 有效期,单位分钟
     */
    public  void setValueExpire(final String key, final Object value,final long timeout) {

        redisTemplate.opsForValue().set(key, value,timeout,TimeUnit.MINUTES);
    }


    /**
     * 获取普通对象
     *
     * @param key 键
     * @return 对象
     */
    public  Object getValue(final String key) {

        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 确定哈希hashKey是否存在
     *
     * @param key 键
     * @param hkey hash键
     * @return true=存在;false=不存在
     */
    public  boolean hasHashKey(final String key,String hkey) {

        Boolean ret = redisTemplate.opsForHash().hasKey(key,hkey);
        return ret != null && ret;
    }

    /**
     * 往Hash中存入数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @param value 值
     */
    public  void hashPut(final String key, final String hKey, final Object value) {

        redisTemplate.opsForHash().put(key, hKey, value);
    }

    /**
     * 往Hash中存入多个数据
     *
     * @param key Redis键
     * @param values Hash键值对
     */
    public  void hashPutAll(final String key, final Map<String, Object> values) {

        redisTemplate.opsForHash().putAll(key, values);
    }

    /**
     * 获取Hash中的数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @return Hash中的对象
     */
    public  Object hashGet(final String key, final String hKey) {

        return redisTemplate.opsForHash().get(key, hKey);
    }

    /**
     * 获取Hash中的数据
     *
     * @param key Redis键
     * @return Hash对象
     */
    public  Map<Object, Object> hashGetAll(final String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 获取多个Hash中的数据
     *
     * @param key Redis键
     * @param hKeys Hash键集合
     * @return Hash对象集合
     */
    public  List<Object> hashMultiGet(final String key, final Collection<Object> hKeys) {

        return redisTemplate.opsForHash().multiGet(key, hKeys);
    }

    /**
     * 删除Hash中的数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @return Hash对象集合
     */
    public  long hashDeleteKeys(final String key, final String hKey) {

        return redisTemplate.opsForHash().delete(key,hKey);
    }

    // 存储Set相关操作

    /**
     * 往Set中存入数据
     *
     * @param key Redis键
     * @param values 值
     * @return 存入的个数
     */
    public  long setSet(final String key, final Object... values) {
        Long count = redisTemplate.opsForSet().add(key, values);
        return count == null ? 0 : count;
    }

    /**
     * 删除Set中的数据
     *
     * @param key Redis键
     * @param values 值
     * @return 移除的个数
     */
    public  long setDel(final String key, final Object... values) {
        Long count = redisTemplate.opsForSet().remove(key, values);
        return count == null ? 0 : count;
    }

    /**
     * 获取set中的所有对象
     *
     * @param key Redis键
     * @return set集合
     */
    public   Set<Object> getSetAll(final String key) {
        return redisTemplate.opsForSet().members(key);
    }

    // 存储ZSet相关操作

    /**
     * 往ZSet中存入数据
     *
     * @param key Redis键
     * @param values 值
     * @return 存入的个数
     */
    public  long zsetSet(final String key, final Set<ZSetOperations.TypedTuple<Object>> values) {
        Long count = redisTemplate.opsForZSet().add(key, values);
        return count == null ? 0 : count;
    }
    /**
     * 获取所有zset数据
     * @param key Redis键
     */
    public Set<ZSetOperations.TypedTuple<Object>> zgetSetAll(final String key) {
        return redisTemplate.opsForZSet().rangeWithScores(key,0,-1);
    }
    /**
     * 获取指定区间的元素,注意是区间不是score
     * @param start 开始位置
     * @param end 结束位置
     * @param key Redis键
     */
    public  Set<ZSetOperations.TypedTuple<Object>> zgetSet(final String key,long start,long end) {
        return redisTemplate.opsForZSet().rangeWithScores(key,start,end);
    }

    /**
     * 通过score区间获取zset数据
     * @param min 最小分数
     * @param max 最大分数
     * @param key Redis键
     */
    public  Set<ZSetOperations.TypedTuple<Object>> zgetSetbyScore(final String key,double min, double max) {
        return redisTemplate.opsForZSet().rangeByScoreWithScores(key,min,max);
    }
    /**
     * 删除ZSet中的数据
     *
     * @param key Redis键
     * @param values 值
     * @return 移除的个数
     */
    public  long zsetDel(final String key, Object... values) {
        Long count = redisTemplate.opsForZSet().remove(key, values);
        return count == null ? 0 : count;
    }

    // 存储List相关操作

    /**
     * 往List中存入数据
     *
     * @param key Redis键
     * @param value 数据
     * @return 存入的个数
     */
    public  long listPush(final String key, final Object value) {
        Long count = redisTemplate.opsForList().rightPush(key, value);
        return count == null ? 0 : count;
    }

    /**
     * 往List中存入多个数据
     *
     * @param key Redis键
     * @param values 多个数据
     * @return 存入的个数
     */
    public  long listPushAll(final String key, final Collection<Object> values) {
        Long count = redisTemplate.opsForList().rightPushAll(key, values);
        return count == null ? 0 : count;
    }

    /**
     * 往List中存入多个数据
     *
     * @param key Redis键
     * @param values 多个数据
     * @return 存入的个数
     */
    public  long listPushAll(final String key, final Object... values) {
        Long count = redisTemplate.opsForList().rightPushAll(key, values);
        return count == null ? 0 : count;
    }

    /**
     * 从List中获取begin到end之间的元素
     *
     * @param key Redis键
     * @param start 开始位置
     * @param end 结束位置(start=0,end=-1表示获取全部元素)
     * @return List对象
     */
    public  List<Object> listGet(final String key, final int start, final int end) {
        return redisTemplate.opsForList().range(key, start, end);
    }


}

操作示例

import com.zx.zhuangxiu.cache.RedisUtils;
import com.zx.zhuangxiu.pojo.Money;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.*;
/**
 * 创 建 人 : wangsheng 创建日期:2020年3月
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class tt {
    @Autowired
    RedisUtils redisUtil;

    @Test
    public void insertMoney() {
        //添加key,value
        redisUtil.setValue("key", "key");

        //添加对象
        Money money=new Money();
        money.setId(1);
        Money money2=new Money();
        redisUtil.setValue("money",money);
        money2= (Money) redisUtil.getValue("money");
        System.out.println(money2.getId());

        //获取key,value
        redisUtil.getValue("key");

        //删除key,value
        redisUtil.delKey("key");

        //批量删除
        List<String> list = new ArrayList<>();
        list.add("key");
        list.add("key2");
        redisUtil.delKeys(list);

        //往Hash中存入数据
        redisUtil.hashPut("hash", "map", "demohash");

        //往Hash中存入多个数据
        Map<String, Object> map = new HashMap<>();
        map.put("map1", "map11");
        map.put("map2", "map22");
        redisUtil.hashPutAll("hash", map);

        //获取hash数据
        redisUtil.hashGet("hash", "map");

        //获取Hash中的数据
        redisUtil.hashGetAll("hash");

        //获取多个Hash中的数据
        Collection<Object> hashlist = new ArrayList<>();
        hashlist.add("map1");
        hashlist.add("map2");
        redisUtil.hashMultiGet("hash", hashlist);

        //删除Hash中的数据
        redisUtil.hashDeleteKeys("hash", "map1");

        //往Set中存入数据
        redisUtil.setSet("set", "key1", "key2", "keyn");

        //获取set中的所有对象
        Set<Object> set = new HashSet<>();
        set = redisUtil.getSetAll("set");
        Iterator<Object> iterable = set.iterator();
        while (iterable.hasNext()) {
            Object cc = iterable.next();
            System.out.println(cc);
        }

        //删除Set中的数据
        redisUtil.setDel("set", "key1");

        //往ZSet中存入数据
        Set<ZSetOperations.TypedTuple<Object>> typedTupleSet = new HashSet<ZSetOperations.TypedTuple<Object>>();
        ZSetOperations.TypedTuple<Object> typedTuple1 = new DefaultTypedTuple<Object>("E",6.0);
        ZSetOperations.TypedTuple<Object> typedTuple2 = new DefaultTypedTuple<Object>("F",7.0);
        ZSetOperations.TypedTuple<Object> typedTuple3 = new DefaultTypedTuple<Object>("G",5.0);
        ZSetOperations.TypedTuple<Object> typedTuple4 = new DefaultTypedTuple<Object>("J",8.0);
        typedTupleSet.add(typedTuple1);
        typedTupleSet.add(typedTuple2);
        typedTupleSet.add(typedTuple3);
        typedTupleSet.add(typedTuple4);
       redisUtil.zsetSet("zset", typedTupleSet);
       //获取所有zset数据
        Set<ZSetOperations.TypedTuple<Object>> typedTupleSet2 = redisUtil.zgetSetAll("zset");
        Iterator<ZSetOperations.TypedTuple<Object>> iterator1 = typedTupleSet2.iterator();
        while (iterator1.hasNext()){
            ZSetOperations.TypedTuple<Object> typedTuple = iterator1.next();
            Object value = typedTuple.getValue();
            double score = typedTuple.getScore();
            System.out.println("通过rangeWithScores(K key, long start, long end)方法获取RedisZSetCommands.Tuples的区间值:" + value + "---->" + score );
        }

        //获取所有zset获取指定区间的数据
        Set<ZSetOperations.TypedTuple<Object>> typedTupleSet1 = redisUtil.zgetSet("zset",1,2);
        Iterator<ZSetOperations.TypedTuple<Object>> iterator = typedTupleSet1.iterator();
        while (iterator.hasNext()){
            ZSetOperations.TypedTuple<Object> typedTuple = iterator.next();
            Object value = typedTuple.getValue();
            double score = typedTuple.getScore();
            System.out.println("通过rangeWithScores(K key, long start, long end)方法获取RedisZSetCommands.Tuples的区间值:" + value + "---->" + score );
        }

        //通过score区间获取zset数据
        Set<ZSetOperations.TypedTuple<Object>> typedTupleSet3 = redisUtil.zgetSetbyScore("zset",6.0,7.0);
        Iterator<ZSetOperations.TypedTuple<Object>> iterator3 = typedTupleSet3.iterator();
        while (iterator3.hasNext()){
            ZSetOperations.TypedTuple<Object> typedTuple = iterator3.next();
            Object value = typedTuple.getValue();
            double score = typedTuple.getScore();
            System.out.println("通过rangeWithScores(K key, long start, long end)方法获取RedisZSetCommands.Tuples的区间值:" + value + "---->" + score );
        }

         //删除zset数据
       redisUtil.zsetDel("zset","E");



    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
RedisTemplate是Spring Data Redis提供的模板类,用于简化Redis操作。而RedisUtils是一个Redis工具类,封装了一些常用的Redis操作,可以方便地进行数据存取。 基于RedisTemplateRedisUtils,需要在RedisTemplate的基础上封装一些常用的操作。首先需要引入Spring Data Redis的依赖,并注入RedisTemplate对象。 ```java @Autowired private RedisTemplate<String, Object> redisTemplate; ``` 然后可以封装一些常用的操作,例如设置缓存、获取缓存和删除缓存。其中,使用RedisTemplate的opsForValue()方法获取ValueOperations对象,然后可以调用set、get、delete等方法进行操作。 ```java public class RedisUtils { @Autowired private RedisTemplate<String, Object> redisTemplate; /** * 设置缓存 * @param key 键 * @param value 值 * @param expireTime 过期时间(秒) */ public void set(String key, Object value, long expireTime) { ValueOperations<String, Object> ops = redisTemplate.opsForValue(); ops.set(key, value, expireTime, TimeUnit.SECONDS); } /** * 获取缓存 * @param key 键 * @return 值 */ public Object get(String key) { ValueOperations<String, Object> ops = redisTemplate.opsForValue(); return ops.get(key); } /** * 删除缓存 * @param key 键 */ public void delete(String key) { redisTemplate.delete(key); } // 其他封装操作... } ``` 除了缓存操作RedisUtils还可以封装一些其他操作,例如列表、集合、哈希表和有序集合等操作。这些操作可以使用RedisTemplate的opsForList、opsForSet、opsForHash和opsForZSet方法获取相应的操作对象,然后进行操作。 综上可知,基于RedisTemplateRedisUtils需要先引入Spring Data Redis的依赖,注入RedisTemplate对象,然后封装常用的缓存和其他操作。这些操作可以通过RedisTemplate的相关方法进行封装

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

今朝花落悲颜色

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值