使用spring-boot-starter-data-redis来操作redis时,RedisTemplate一些常用方法的工具类,提高开发效率。
package com.hmdp.utils;
import cn.hutool.core.util.BooleanUtil;
import com.hmdp.dto.GeoRadiusDto;
import lombok.NonNull;
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.connection.RedisStringCommands;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtils {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private StringRedisTemplate stringRedisTemplate;
public <T> T execute(RedisScript<T> script, List<String> keys, Object... args) {
return stringRedisTemplate.execute(script,keys,args);
}
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean expire(String key, long time, TimeUnit timeUnit) {
try {
if (time > 0) {
redisTemplate.expire(key, time, timeUnit);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
}
}
}
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
public boolean setNx(String key,Object value,long time, TimeUnit unit){
try {
if (time==-1) {
unit=null;
}
Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, value,time,unit);
return BooleanUtil.isTrue(flag);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean hmset(String key, Map<String, Object> map, long time, TimeUnit timeUnit) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time, timeUnit);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean hset(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
public Set<Object> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public boolean sIsMemberKey(String key, Object value) {
try {
Boolean flag = redisTemplate.opsForSet().isMember(key, value);
return BooleanUtil.isTrue(flag);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long sAdd(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public long sSetAndTime(String key, long time, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0) expire(key, time);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public long setRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public Set<Object> sUnion(List<String> listKeys) {
try {
return redisTemplate.opsForSet().union(listKeys);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Set<Object> sIntersect(List<String> listKeys) {
try {
return redisTemplate.opsForSet().intersect(listKeys);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Set<Object> sDiff(List<String> listKeys) {
try {
return redisTemplate.opsForSet().difference(listKeys);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public boolean zSetAdd(String key, String value, double score) {
try {
Boolean aBoolean = stringRedisTemplate.opsForZSet().add(key, value, score);
return BooleanUtil.isTrue(aBoolean);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean zRem(String key, Object... values) {
try {
Long aLong = redisTemplate.opsForZSet().remove(key, values);
return aLong!=null?true:false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public Double incrScore(String key, String value, double score) {
try {
return stringRedisTemplate.opsForZSet().incrementScore(key, value, score);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Double score(String key, String value) {
try {
return stringRedisTemplate.opsForZSet().score(key, value);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Long zSize(String key) {
try {
return stringRedisTemplate.opsForZSet().zCard(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Long zRank(String key, String value) {
try {
return stringRedisTemplate.opsForZSet().rank(key, value);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Set<String> zRange(String key, int start, int end) {
try {
return stringRedisTemplate.opsForZSet().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Set<ZSetOperations.TypedTuple<String>> zRangeWithScore(String key, int start, int end) {
try {
return stringRedisTemplate.opsForZSet().rangeWithScores(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Set<String> revRange(String key, int start, int end) {
try {
return stringRedisTemplate.opsForZSet().reverseRange(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Set<String> zSortRangeByScore(String key, double min, double max,long offset,long count) {
try {
return stringRedisTemplate.opsForZSet().rangeByScore(key, min, max,offset,count);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Set<String> zSortRevRangeByScore(String key, double min, double max,long offset,long count) {
try {
return stringRedisTemplate.opsForZSet().reverseRangeByScore(key, min, max,offset,count);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Set<ZSetOperations.TypedTuple<String>> zSortRevRangeByScoreWithScores(String key, double min, double max,long offset,long count) {
try {
return stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, min, max,offset,count);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public List<Object> lGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0) expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean lSetAll(String key, List<?> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0) expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean lUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long lRemove(String key, long count, Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public Long geoAdd(String key, Point point, String member) {
return stringRedisTemplate.opsForGeo().geoAdd(key, point, member);
}
public Long geoAddGeoLocation(String key,List<RedisGeoCommands.GeoLocation<Object>> locations) {
return redisTemplate.opsForGeo().add(key, locations);
}
public Long geoRemove(String key, String... members) {
return stringRedisTemplate.opsForGeo().geoRemove(key, members);
}
public List<Point> geoPos(String key, String... members) {
return stringRedisTemplate.opsForGeo().geoPos(key, members);
}
public List<String> geoHash(String key, String... members) {
return stringRedisTemplate.opsForGeo().geoHash(key, members);
}
public Double geoDist(String key, String member1, String member2, Metric metric) {
return stringRedisTemplate.opsForGeo().geoDist(key, member1, member2, metric).getValue();
}
public List<GeoRadiusDto> geoSearchByPoint(String key, Point center, Double radius, Metric metric,Integer maxCount
) {
Distance distance = new Distance(radius, metric);
Circle within = new Circle(center, distance);
GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults = null;
if (maxCount!=null) {
geoResults=stringRedisTemplate.opsForGeo()
.search(key, GeoReference.fromCircle(within), distance, RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().includeCoordinates().limit(maxCount));
}else{
geoResults=stringRedisTemplate.opsForGeo()
.search(key, GeoReference.fromCircle(within), distance,RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().includeCoordinates());
}
List<GeoResult<RedisGeoCommands.GeoLocation<String>>> geoResultList = geoResults.getContent();
if(geoResultList==null || geoResultList.isEmpty()){
return null;
}
List<GeoRadiusDto> radiusDtos = new ArrayList<GeoRadiusDto>(geoResultList.size());
for(GeoResult<RedisGeoCommands.GeoLocation<String>> geoResult:geoResultList){
String name = geoResult.getContent().getName();
GeoRadiusDto radiusDto = new GeoRadiusDto();
Point point = geoResult.getContent().getPoint();
radiusDto.setKey(key);
radiusDto.setMember(name);
radiusDto.setX(point.getX());
radiusDto.setY(point.getY());
radiusDto.setDistance(geoResult.getDistance());
radiusDtos.add(radiusDto);
}
return radiusDtos;
}
public List<GeoRadiusDto> geoSearchByMember(String key, String member, Double radius, Metric metric,Integer maxCount) {
Distance distance = new Distance(radius, metric);
GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults = null;
if (maxCount!=null) {
geoResults=stringRedisTemplate.opsForGeo()
.search(key, GeoReference.fromMember(member), distance,
RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs()
.includeDistance().includeCoordinates().limit(maxCount));
}else{
geoResults=stringRedisTemplate.opsForGeo()
.search(key, GeoReference.fromMember(member), distance,
RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs()
.includeDistance().includeCoordinates());
}
List<GeoResult<RedisGeoCommands.GeoLocation<String>>> geoResultList = geoResults.getContent();
if(geoResultList==null || geoResultList.isEmpty()){
return null;
}
List<GeoRadiusDto> radiusDtos = new ArrayList<GeoRadiusDto>(geoResultList.size());
for(GeoResult<RedisGeoCommands.GeoLocation<String>> geoResult:geoResultList){
String name = geoResult.getContent().getName();
Point point = geoResult.getContent().getPoint();
GeoRadiusDto radiusDto = new GeoRadiusDto();
radiusDto.setKey(key);
radiusDto.setMember(name);
radiusDto.setX(point.getX());
radiusDto.setY(point.getY());
radiusDtos.add(radiusDto);
}
return radiusDtos;
}
public void setBit(String key, long offset, boolean value) {
try {
Boolean aBoolean = stringRedisTemplate.opsForValue().setBit(key, offset, value);
} catch (Exception e) {
e.printStackTrace();
}
}
public Long bitField(String key, int bits, long offset){
try {
List<Long> longs = stringRedisTemplate.opsForValue().bitField(key,
BitFieldSubCommands.create().
get(BitFieldSubCommands.BitFieldType.unsigned(bits)).valueAt(offset));
if (longs==null || longs.isEmpty()) {
return null;
}
return longs.get(0);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public boolean getBit(String key, long offset) {
try {
Boolean aBoolean = stringRedisTemplate.opsForValue().getBit(key, offset);
return BooleanUtil.isTrue(aBoolean);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public Long bitCountAll(String key) {
try {
return (Long) stringRedisTemplate.execute((RedisCallback) con -> con.bitCount(key.getBytes()));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Long bitCount(String key, Long start, Long end) {
try {
return (Long) stringRedisTemplate.execute((RedisCallback) con -> con.bitCount(key.getBytes(), start, end));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public List<MapRecord<String, Object, Object>> xReadGroup(String groupName,String consumerName,
int count,long seconds,String streamsKey,
ReadOffset readOffset){
if (0 == count) {
return null;
}
StreamReadOptions block = StreamReadOptions.empty().count(count).block(Duration.ofSeconds(seconds));
if (seconds==0) {
block=StreamReadOptions.empty().count(count);
}
List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().
read(Consumer.from(groupName, consumerName),block,StreamOffset.create(streamsKey, readOffset));
return list;
}
public long xAck(String streamsKey, String groupName, String... recordIds){
Long ackNums = stringRedisTemplate.opsForStream().acknowledge(streamsKey, groupName, recordIds);
if (null==ackNums) {
return 0;
}
return ackNums;
}
}