2021-09-26

redisTemplate操作手册

package common.redis.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.DataType;
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;


@Component
public class StringJedisUtil {

    private Logger logger = LoggerFactory.getLogger(StringJedisUtil.class);

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

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

    /**
     * 设置key的有效时间
     * @param key
     * @param time
     * @param timeUnit
     * @return
     */
    public boolean expire(String key, long time, TimeUnit timeUnit){
        Boolean expire = false;
        try{
            if(time>0){
                expire = redisTemplate.expire(key, time, timeUnit);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return expire;
    }

    public Boolean expire(String key, Date date){
        boolean expireStatus = false;
        try {
            if(StringUtils.isNotBlank(key)){
                expireStatus = redisTemplate.expireAt(key,date);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return expireStatus;
    }

    /**
     * 获取key的过期时间
     * 0为永久有效
     * 单位为秒
     * @param key
     * @return
     */
    public Long getExpires(String key) {
        return redisTemplate.getExpire(key);
    }

    /**
     * 获取key到期时间并且指定返回的时间单位 秒 小时 毫秒 分钟等
     * @param key
     * @param timeUnit
     * @return
     */
    public long getExpres(String key,TimeUnit timeUnit){
        return redisTemplate.getExpire(key,timeUnit);
    }

    /**
     * 判断key是否存在
     * @param key
     * @return
     */
    public Boolean hasKey(String key){
       return redisTemplate.hasKey(key);
    }

    /**
     * 获取key对应的val值
     * @param key
     * @return
     */
    public Object getVal(String key){
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 删除单个key或多个key
     * @param key
     */
    public void delete(String... key){
        if(key.length > 0 && key != null){
            if(key.length == 1){
                redisTemplate.delete(key[0]);
            }else {
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }

    /**
     * 把key转换为byte[]数组
     * @param key
     * @return
     */
    public byte[] dump(String key){
        return redisTemplate.dump(key);
    }

    /**
     * 查找匹配的key值,返回一个Set集合类型
     * @param patten
     * @return
     */
    public Set<String> getPatternKey(String patten) {
        return redisTemplate.keys(patten);
    }

    /**
     * 修改redis中key的名称
     * @param oldKey
     * @param newKey
     */
    public void renameKey(String oldKey,String newKey){
        redisTemplate.rename(oldKey,newKey);
    }

    /**
     * 返回redis中key值的类型
     * @param key
     * @return
     */
    public DataType getKeyType(String key){
         return redisTemplate.type(key);
    }

    /**
     * 如果旧值存在则替换为新值
     * @param oldKey
     * @param newKey
     * @return
     */
    public Boolean renameIfAbsent(String oldKey,String newKey){
        return redisTemplate.renameIfAbsent(oldKey,newKey);
    }

    /**
     * 从redis中随机取出一个key
     * @return
     */
    public String randomKey(){
        return redisTemplate.randomKey();
    }

    /**
     * 将key持久化保存
     * @param key
     * @return
     */
    public Boolean persistKey(String key){
        return redisTemplate.persist(key);
    }

    /**
     * 将key移到指定的数据库中
     * @param key
     * @param dataIndex
     * @return
     */
    public Boolean move(String key,Integer dataIndex){
        return redisTemplate.move(key,dataIndex);
    }

    /**
     * 设置key值
     * @param key
     * @param val
     */
    public void setKey(String key,Object val){
        redisTemplate.opsForValue().set(key,val);
    }

    /**
     * 设置key的val并设置过期时间
     * @param key
     * @param val
     * @param time
     * @param unit
     */
    public void setValExpire(String key,Object val,Long time,TimeUnit unit){
        redisTemplate.opsForValue().set(key,val,time,unit);
    }

    /**
     * 返回key指定的长度部分
     * @param key
     * @param start
     * @param end
     * @return
     */
    public String getCharacterRange(String key,Integer start,Integer end){
        return redisTemplate.opsForValue().get(key,start,end);
    }

    /**
     * 获取多个key的值
     * @param keys
     * @return
     */
    public List<Object> multiGet(Collection<String> keys){
        return redisTemplate.opsForValue().multiGet(keys);
    }

    /**
     * 在key值原有的基础上进行追加
     * @param key
     * @param val
     */
    public void append(String key,String val){
        redisTemplate.opsForValue().append(key, val);
    }

    /**
     * 已增量的方式添加double
     * @param key
     * @param increment
     * @return
     */
    public Double incrDouble(String key,Double increment){
        return redisTemplate.opsForValue().increment(key,increment);
    }

    /**
     * 负数自减,正数自增
     * @param key
     * @param increment
     * @return
     */
    public Long incrByLong(String key,Integer increment){
        return redisTemplate.opsForValue().increment(key,increment);
    }

    /**
     * 获取key的length
     * @param key
     * @return
     */
    public long getKeyLen(String key){
        return redisTemplate.opsForValue().size(key);
    }

    /**
     * 设置map集合到redis中
     * 批量设置 k v 如果key存在则覆盖val
     * @param map
     */
    public void multiSet(Map map){
        redisTemplate.opsForValue().multiSet(map);
    }

    /**
     * 如果map集合中的Key存在则不做任何处理,(注意: 一个key都不重复的情况下才会执行此操作)
     * 如果不存在则添加
     * @param map
     * @return
     */
    public boolean multiSetIfAbsent(Map map){
        return redisTemplate.opsForValue().multiSetIfAbsent(map);
    }

    /**
     * 替换对应key的val值 并且返回旧的val
     * @param key
     * @param val
     * @return
     */
    public Object getAndSet(String key,Object val){ return redisTemplate.opsForValue().getAndSet(key,val);}

}
package common.redis.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class ListJedisUtil {


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 从list左边添加元素
      * @param key
     * @param val
     * @return
     */
    public long lPush(String key,Object val){
        return redisTemplate.opsForList().leftPush(key, val);
    }

    /**
     * 新增数据实现
     * @param key
     * @param val
     * @return
     */
    public long lPushAll(String key,Object... val){
        return redisTemplate.opsForList().leftPushAll(key,val);
    }

    /**
     * 新增集合
     * @param key
     * @param collection
     * @return
     */
    public long lPushAll(String key, Collection collection){
        return redisTemplate.opsForList().leftPushAll(key,collection);
    }

    /**
     * 如果list存在则往里面添加元素
     * @param key
     * @param val
     * @return
     */
    public long l(String key,Object val){
        return redisTemplate.opsForList().leftPushIfPresent(key,val);
    }

    /**
     * 从list数据左边添加在某个值的后面
     * @param key
     * @param val
     * @param val1
     * @return
     */
    public long lPush(String key,Object val,Object val1){
        return redisTemplate.opsForList().leftPush(key,val,val1);
    }

    /**
     *从list右边添加元素
     * @param key
     * @param val
     * @return
     */
    public long rPush(String key,Object val){return redisTemplate.opsForList().rightPush(key,val);}

    /**
     * 从list右边开始新增数组
     * @param key
     * @param val
     * @return
     */
    public long rPush(String key,Object... val){
        return redisTemplate.opsForList().leftPushAll(key,val);
    }

    /**
     * 从list右边添加一个集合
     * @param key
     * @param collection
     * @return
     */
    public long rPushAll(String key,Collection collection){
        return redisTemplate.opsForList().leftPushAll(key,collection);
    }

    /**
     * 获取指定索引位置的值, index为-1时,表示返回的是最后一个;当index大于实际的列表长度时,返回null
     * @param key
     * @param index
     * @return
     */
    public Object index(String key,long index){
        return redisTemplate.opsForList().index(key,index);
    }

    /**
     * list范围性查找
     * @param key
     * @param start
     * @param end
     * @return
     */
    public List rangList(String key,int start,int end){
        return redisTemplate.opsForList().range(key,start,end);
    }

    /**
     * 获取key的长度
     * @param key
     * @return
     */
    public long listLen(String key){
        return redisTemplate.opsForList().size(key);
    }

    /**
     * 替换list中某个下标的valv
     * @param key
     * @param index
     * @param val
     */
    public void setListVal(String key,int index,Object val){
        redisTemplate.opsForList().set(key,index,val);
    }

    /**
     * 删除列表中值为value的元素,总共删除count次;
     *
     * 如原来列表为 【1, 2, 3, 4, 5, 2, 1, 2, 5】
     * 传入参数 value=2, count=1 表示删除一个列表中value为2的元素
     * 则执行后,列表为 【1, 3, 4, 5, 2, 1, 2, 5】
     * count < 0,从右开始,count > 0,从左开始,count = 0,全部
     *
     * @param key
     * @param value
     * @param count
     */
    public void remove(String key, String value, int count) {
        redisTemplate.opsForList().remove(key, count, value);
    }

    /**
     * 删除list首尾,只保留 [start, end] 之间的值
     *
     * @param key
     * @param start
     * @param end
     */
    public void trim(String key, Integer start, Integer end) {
        redisTemplate.opsForList().trim(key, start, end);
    }

    /**
     * 弹出list最左边的元素
     * @param key
     * @return
     */
    public Object leftPop(String key){
        return redisTemplate.opsForList().leftPop(key);
    }

    /**
     * 弹出左边元素 并设置阻塞时间
     * @param key
     * @param time
     * @param unit
     * @return
     */
    public Object leftPop(String key, Long time, TimeUnit unit){
        return redisTemplate.opsForList().leftPop(key,time,unit);
    }

    /**
     * 弹出列表最右边的元素
     * @param key
     * @return
     */
    public Object rightPop(String key){
        return redisTemplate.opsForList().rightPop(key);
    }

    /**
     * 弹出列表最右边的元素并且设置阻塞时间
     * 注: 阻塞时间为 下次读取距离上次读取的间隔时间
     * @param key
     * @param time
     * @param unit
     * @return
     */
    public Object rightPop(String key,Long time,TimeUnit unit){
        return redisTemplate.opsForList().rightPop(key,time,unit);
    }

}

```cpp
package common.redis.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;
import java.util.Set;

public class SetJedisUtil {

    private static Logger logger = LoggerFactory.getLogger(SetJedisUtil.class);

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增set集合
     * @param key
     * @param val
     * @return
     */
    public long addSet(String key,Object... val){
        long size  = 0;
        try {
           size = redisTemplate.opsForSet().add(key,val);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("新增set集合 {} 失败",key);
        }
        return size;
    }

    /**
     * 移除指定set集合中的val
     * @param key
     * @param val
     * @return
     */
    public long removeSet(String key,Object... val){
        long size = 0;
        try {
            size = redisTemplate.opsForSet().remove(key,val);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("移除set集合中{}失败",key);
        }
        return size;
    }

    /**
     * 计算set集合中的数量
     * @param key
     * @return
     */
    public long countSet(String key){
        long size = 0;
        try {
            size = redisTemplate.opsForSet().size(key);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("计算集合{}数量失败",key);
        }
        return size;
    }

    /**
     * 判断set集合中是否存在某元素
     * @param key
     * @param val
     * @return
     */
    public Boolean hasMemberSet(String key,Object val){
        Boolean exist = false;
        try {
            exist = redisTemplate.opsForSet().isMember(key, val);
        } catch (Exception e) {
            logger.error("[RedisUtils.hasNumberSet] [error]", e);
        }
        return exist;
    }

    /**
     * 随机获取set集合中一个元素
     * @param key
     * @return
     */
    public Object rangMember(String key){
        return redisTemplate.opsForSet().randomMember(key);
    }

    /**
     * 获取set集合中的某些元素 可能重复
     * 指定元素数量
     * @param key
     * @param nums
     * @return
     */
    public List randomMembers(String key,long nums){
        return redisTemplate.opsForSet().randomMembers(key,nums);
    }

    /**
     * 获取set集合中元素数量 指定数量随机选择 不重复
     * @param key
     * @param nums
     * @return
     */
    public Set distinctRandomMembers(String key,Long nums){
        return redisTemplate.opsForSet().distinctRandomMembers(key,nums);
    }

    /**
     * 随机移除集合中的一个元素
     * @param key
     * @return
     */
    public Object popMember(String key){
        return redisTemplate.opsForSet().pop(key);
    }

    /**
     * 随机移除set集合中的元素 注意可以指定元素个数
     * @param key
     * @param nums
     * @return
     */
    public List popMember(String key,long nums){
        return redisTemplate.opsForSet().pop(key, nums);
    }

    /**
     * 获取set集合中的所有数据
     * @param key
     * @return
     */
    public Set<Object> members(String key){
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * 移动集合中的元素到另一个集合中
     * @param key1
     * @param val
     * @param key2
     * @return
     */
    public Boolean moveMember(String key1,Object val,String key2){
        return redisTemplate.opsForSet().move(key1,val,key2);
    }

    /**
     * 获取两个集合key中元素的并集
     * @param key1
     * @param key2
     * @return
     */
    public Set<Object>intersectMember(String key1,String key2){
        return redisTemplate.opsForSet().intersect(key1,key2);
    }

    /**
     * 一个集合与多个集合之间取交集
     *
     * @param key
     * @param key2
     * @return
     */
    public Set<Object> multiIntersectMember(String key, Set<String> key2) {
        return redisTemplate.opsForSet().intersect(key, key2);
    }

    /**
     * 取两个key的交集并且存入第三个key中
     * @param key1
     * @param key2
     * @param key3
     * @return
     */
    public long storeIntersectMember(String key1,String key2,String key3){
        return redisTemplate.opsForSet().intersectAndStore(key1,key2,key3);
    }

    /**
     * 取两个set集合的并集
     * @param key1
     * @param key2
     * @return
     */
    public Set<Object> unionMember(String key1,String key2){
        return redisTemplate.opsForSet().union(key1,key2);
    }

    /**
     * 求并集(一个集合与多个集合之间)
     *
     * @param key1
     * @param keys
     * @return
     */
    public Set<Object> multiUnionMember(String key1, Set<String> keys) {
        return redisTemplate.opsForSet().union(key1, keys);
    }

    /**
     * 取两个集合中的并集并放入第三个key中
     * @param key1
     * @param key2
     * @param key3
     * @return
     */
    public long storeMultiUnionMember(String key1,String key2,String key3){
        return redisTemplate.opsForSet().unionAndStore(key1,key2,key3);
    }

    /**
     * 获取两个key之间的差集
     * @param key1
     * @param key2
     * @return
     */
    public Set<Object> difference(String key1,String key2){
        return redisTemplate.opsForSet().difference(key1,key2);
    }

    /**
     * 获取多个key之间的差集
     * @param key
     * @param keys
     * @return
     */
    public Set<Object> difference(String key,Set<String> keys){
        return redisTemplate.opsForSet().difference(key,keys);
    }

    /**
     * 获取两个key的差集并且放入第三个key中
     * @param key1
     * @param key2
     * @param key3
     * @return
     */
    public long differenceAndStore(String key1,String key2,String key3){
        return redisTemplate.opsForSet().differenceAndStore(key1,key2,key3);
    }

}
package common.redis.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;

import java.util.Collection;
import java.util.Set;

public class ZsetJedisUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加zset集合
     * @param key
     * @param val
     * @param score
     * @return
     */
    public Boolean addZset(String key,Object val,double score){
        return redisTemplate.opsForZSet().add(key,val,score);
    }

    /**
     * Set<ZSetOperations.TypedTuple<String>> set = new HashSet<>();
     * set.add(new DefaultTypedTuple<>("E", 6.0));
     * set.add(new DefaultTypedTuple<>("F", 7.0));
     * set.add(new DefaultTypedTuple<>("G", 8.0));
     * log.debug("key新增{}条数据", zsetVo.add("key", set));
     * @param key
     * @param tuples
     * @return
     */
    public Long addZset(String key, Set<ZSetOperations.TypedTuple<Object>> tuples){
        return redisTemplate.opsForZSet().add(key,tuples);
    }

    /**
     * 获取zset集合数量
     * @param key
     * @return
     */
    public long zsetCount(String key){
        return redisTemplate.opsForZSet().size(key);
    }

    /**
     * 范围性获取集合中的元素
     * 从小到大排序
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Set<Object> rangZset(String key,Long start,Long end){
        return redisTemplate.opsForZSet().range(key,start,end);
    }

    /**
     * 数组式移除集合中的多个元素
     * @param key
     * @param val
     * @return
     */
    public Long removeZset(String key, Object... val){
        return redisTemplate.opsForZSet().remove(key,val);
    }

    /**
     * 移除指定下标元素的属性
     * @param key
     * @param start
     * @param end
     * @return
     */
    public long remove(String key,long start,long end){ return redisTemplate.opsForZSet().removeRange(key,start,end);}

    /**
     * 获取集合中对应元素的score值
     * @param key
     * @param val
     * @return
     */
    public Double zsetScore(String key,Object val){
        return redisTemplate.opsForZSet().score(key,val);
    }

    /**
     * 对指定集合范围性的元素进行排序
     * 注: 从小到大排序
     * @param key
     * @param val1
     * @param val2
     * @return
     */
    public Set<Object> rangeByScore(String key,Double val1,Double val2){
        return redisTemplate.opsForZSet().rangeByScore(key,val1,val2);
    }

    /**
     * 从小到大排序
     * 指定数据范围指定取元素范围
     * @param key
     * @param val1
     * @param val2
     * @param start
     * @param end
     * @return
     */
    public Set<Object> rangeByScore(String key,Double val1,Double val2,long start,long end){
        return redisTemplate.opsForZSet().rangeByScore(key,val1,val2,start,end);
    }

    /**
     * 对于score属性元素的增加
     * @param key
     * @param val
     * @param score
     * @return
     */
    public Double addScore(String key,Object val,Double score){
        return  redisTemplate.opsForZSet().incrementScore(key,val,score);
    }

    /**
     * 获取该元素在集合中的排序
     * @param key
     * @param val
     * @return
     */
    public long rank(String key,Object val){
        return redisTemplate.opsForZSet().rank(key,val);
    }

    /**
     * 移除集合中的指定元素
     * @param key
     * @param val
     * @return
     */
    public long remove(String key,Object val){
        return redisTemplate.opsForZSet().remove(key,val);
    }

    /**
     * 获取元素排名 从大到小
     * @param key
     * @param val
     * @return
     */
    public Long reverseRank(String key, Object val){
        return redisTemplate.opsForZSet().reverseRank(key,val);
    }

    /**
     * 从大到小进行排序 范围性取值
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Set reverseRangeWithScores(String key, Long start, long end){
        return redisTemplate.opsForZSet().reverseRangeWithScores(key,start,end);
    }

    /**
     * 从大到小排序
     * @param key
     * @param val
     * @param val2
     * @param start
     * @param end
     * @return
     */
    public Set reverseRangeWithScores(String key,Double val,Double val2,long start,Long end){
        return redisTemplate.opsForZSet().reverseRangeByScore(key,val,val2,start,end);
    }

    /**
     * 移除范围性的元素并从小到大排序
     * log.debug("分数:{}",zsetVo.reverseRangeWithScores("key",1,3).stream().map(ZSetOperations.TypedTuple::getScore).collect(Collectors.toList()));
     * log.debug("元素:{}",zsetVo.reverseRangeWithScores("key",1,3).stream().map(ZSetOperations.TypedTuple::getValue).collect(Collectors.toList()));
     * @param key
     * @param val
     * @param val2
     * @return
     */
   public long removeRangeByScore(String key,Double val,Double val2){
        return redisTemplate.opsForZSet().removeRangeByScore(key,val,val2);
   }

    /**
     * 返回指定分数范围内的元素个数
     * @param key
     * @param val
     * @param val2
     * @return
     */
   public long remove(String key,Double val,Double val2){
       return redisTemplate.opsForZSet().count(key,val,val2);
   }

    /**
     * 计算两个集合中的并集,并存入第三个集合中去, 如果集合中元素相同则score相加
     * @param key1
     * @param key2
     * @param key3
     * @return
     */
   public long unionAndStore(String key1,String key2,String key3){
       return redisTemplate.opsForZSet().unionAndStore(key1,key2,key3);
   }

    /**
     * 计算集合元素的并集 并存储在新的key中
     * @param key
     * @param collection
     * @param newKey
     * @return
     */
   public long unionAndStore(String key,Collection collection,String newKey){
       return redisTemplate.opsForZSet().unionAndStore(key,collection,newKey);
   }

    /**
     * 计算有序集合的交集并存储到新集合中
     * @param key
     * @param key1
     * @param key2
     * @return
     */
   public long intersectAndStore(String key,String key1,String key2){
       return redisTemplate.opsForZSet().intersectAndStore(key,key1,key2);
   }

    /**
     * 计算有序集合的交集并且存储新的key
     * @param key
     * @param collection
     * @param newKey
     * @return
     */
   public long intersectAndStore(String key,Collection collection,String newKey){
       return redisTemplate.opsForZSet().intersectAndStore(key,collection,newKey);
   }
}
package common.redis.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.*;

public class HashJedisUtil {

    private Logger logger = LoggerFactory.getLogger(HashJedisUtil.class);

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

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


    /**
     * 如何避免hash中bigKey的出现
     * 采用分段存储
     * 1、对数据库中用户id进行取余计算 id/10000 这样 把数据分段存储在一万个hash中从而避免bigKey出现
     */


    /**
     * 已map的形式添加hash
     * @param key
     * @param map
     */
    public void putAll(String key,Map map){
        redisTemplate.opsForHash().putAll(key,map);
    }

    /**
     * 获取hash key中的数量
     * @param key
     * @return
     */
    public long hashSize(String key){
        return redisTemplate.opsForHash().size(key);
    }

    /**
     * 获取该key的所有值
     * @param key
     * @return
     */
    public List<Object> getHashVal(String key){
        return redisTemplate.opsForHash().values(key);
    }

    /**
     * 获取hash表中所有的key
     * @param key
     * @return
     */
    public Set<Object> getHashKeys(String key){
        return redisTemplate.opsForHash().keys(key);
    }

    /**
     * 获取某一个hash中的key值
     * @param mapKey
     * @param key
     * @return
     */
    public Object getHashKey(String mapKey,String key){
        return redisTemplate.opsForHash().get(mapKey,key);
    }

    /**
     * 返回hash中所有的map
     * @param key
     * @return
     */
    public Map<Object, Object> resultMapList(String key){return redisTemplate.opsForHash().entries(key);}

    /**
     * 判断hash中是否存在某一个key
     * @param key
     * @param hashKey
     * @return
     */
    public Boolean hashKey(String key,String hashKey){
        return redisTemplate.opsForHash().hasKey(key,hashKey);
    }

    /**
     * 新增hash
     * @param key
     * @param hashKey
     * @param val
     */
    public void hashPut(String key,String hashKey,Object val){
        redisTemplate.opsForHash().put(key,hashKey,val);
    }

    /**
     * 获取hash的长度
     * @param key
     * @return
     */
    public Long getHashLen(String key){
        return redisTemplate.opsForHash().size(key);
    }

    /**
     * 使hash中的key以double自增
     * @param key
     * @param hashKey
     * @param nums
     * @return
     */
    public Double increment(String key,String hashKey,Double nums){
       return redisTemplate.opsForHash().increment(key, hashKey, nums);
    }

    /**
     * 已整数的方式使hash中的值进行增加
     * @param key
     * @param hashKey
     * @param nums
     * @return
     */
    public long increment(String key,String hashKey,Long nums){
        return redisTemplate.opsForHash().increment(key,hashKey,nums);
    }

    /**
     * 获取hash中的值以集合的方式获取
     * List<Object> list = new ArrayList<Object>();
     * list.add("map1");
     * list.add("map2");
     * @param key
     * @param collection
     * @return
     */
    public List mu(String key,Collection collection){
        return redisTemplate.opsForHash().multiGet(key,collection);
    }

    /**
     * 如果hash中不存在则添加,如果存在则不作任何操作
     * @param key
     * @param hashKey
     * @param val
     * @return
     */
    public Boolean putIfAbsent(String key,String hashKey,Object val){
        return redisTemplate.opsForHash().putIfAbsent(key,hashKey,val);
    }

    /**
     * 多个key删除 hash
     * @param key
     * @param hashKeys
     * @return
     */
    public long hashDel(String key,Object... hashKeys){
        return redisTemplate.opsForHash().delete(key,hashKeys);
    }
}
package common.redis.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;

public class BitMapJedisUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 设置bitmap值
     * @param key
     * @param val
     * @param status
     * @return
     */
    public Boolean setBitMap(String key,long val,Boolean status){
        return redisTemplate.opsForValue().setBit(key,val,status);
    }

    /**
     * 获取bitmap的val
     * @param key
     * @param val
     * @return
     */
    public Boolean getBitMap(String key, Long val){
        return redisTemplate.opsForValue().getBit(key,val);
    }

    /**
     * bitcount获取所有的签到数量
     * @param key
     * @return
     */
    public int countBitMap(String key){
        return (int)redisTemplate.execute((RedisCallback<Long>)con -> con.bitCount(key.getBytes()));
    }

    /**
     * 计算用户连续签到
     * @param key
     * @param start
     * @param end
     * @return
     */
    public List<Long> bitFiled(String key,int start,int end){
        return (List<Long>) redisTemplate.execute((RedisCallback<List<Long>>)
                con -> con.bitField(key.getBytes(), BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.signed(start))
                                .valueAt(end)));
    }

    /**
     * redis计数器
     * @param key
     * @param val
     * @return
     */
    public Boolean addHyperLogLog(String key,Object val){
        return redisTemplate.opsForHyperLogLog().add(key,val)>0;
    }

    /**
     * redis计数器
     * @param key
     * @param val
     * @return
     */
    public Boolean addHyperLogLog(String key,Object... val){
        return redisTemplate.opsForHyperLogLog().add(key,val)>0;
    }

    /**
     * 计算hyperLog的数量
     * @param key
     * @return
     */
    public Long hyperLogCounts(String key){
        return redisTemplate.opsForHyperLogLog().size(key);
    }

    /**
     * 将多个key合并存入newKey中
     * @param newKey
     * @param keys
     * @return
     */
    public Boolean mergeHyperLog(String newKey,String... keys){
        return redisTemplate.opsForHyperLogLog().union(newKey,keys)>0;
    }

    /**
     * 新增地理位置
     * @param key
     * @param point
     * @param city
     * @return
     * Long addedNum = redisTemplate.opsForGeo().add("geo", new Point(113.27, 23.13), "广州");
     */
    public Long addGeo(String key, Point point, String city){
        return redisTemplate.opsForGeo().add(key,point,city);
    }

    /**
     * 返回多个城市的经纬度信息
     * @param key
     * @param city
     * @return
     */
    public List<Point> points(String key,String... city){
        return redisTemplate.opsForGeo().position(key,city);
    }

    /**
     * 返回两个城市之间的距离
     * @param key
     * @param city
     * @return
     */
    public Distance distanceKilometers(String key, String city, String city1, RedisGeoCommands.DistanceUnit unit){
        Distance distance = redisTemplate.opsForGeo()
                .distance(key,city,city1,unit);
        return distance;
    }

    /**
     * 计算经纬度方圆多少范围内的地理位置信息
     * @param key
     * @param lon
     * @param lat
     * @param scope
     * @param metrics
     * @param limit
     */
    public GeoResults<RedisGeoCommands.GeoLocation<String>> rangeOfInformation(String key,double lon,double lat,int scope,Metrics metrics,int limit){
        Circle circle = new Circle(new Point(lon, lat), new Distance(scope,metrics));//Point(经度, 纬度) Distance(距离量, 距离单位)
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().includeCoordinates().sortAscending().limit(limit);
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = redisTemplate.opsForGeo()
                .radius(key,circle,args);//params: key, Circle, GeoRadiusCommandArgs
        return results;
    }

    /**
     * 已某个城市为中心查询方圆多少长度内的地理位置信息
     * @param key
     * @param city
     * @param scope
     * @param metrics
     * @param limit
     * @return
     */
    public GeoResults<RedisGeoCommands.GeoLocation<String>> cityScope(String key,String city,int scope,Metrics metrics,int limit){
        Distance distance = new Distance(scope,metrics);//params: 距离量, 距离单位
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().includeCoordinates().sortAscending().limit(limit);
        GeoResults<RedisGeoCommands.GeoLocation<String>>  results = redisTemplate.opsForGeo() .radius(key,city,distance,args);//params: key, 地方名称, Circle, GeoRadiusCommandArgs
        return results;
    }

    /**
     * 移除地理位置信息
     * @param key
     * @param city
     * @return
     */
    public boolean removeGeo(String key, String city){
        return redisTemplate.opsForGeo().remove(key,city) > 0;
    }

    public Boolean removeGeo(String key,String... city){
        return redisTemplate.opsForGeo().remove(key,city) > 0;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Pursue?????

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

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

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

打赏作者

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

抵扣说明:

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

余额充值