关于redis在项目中常见应用采用自写接口
接口CacheService ,写方法对应每个功能;
实现类 RedisCacheServiceImpl,重写方法,写每个功能具体实现逻辑;
注入对应StringRedisTemplate;
@Autowired
private StringRedisTemplate template;
1、根据key获取String类型的value
String codeValue = cacheService.getValue(codeKey);
@Override
public String getValue(String key) {
ValueOperations<String, String> ops = template.opsForValue();
return ops.get(key);
}
2、向redis中存string类型的值
cacheService.setKey ( Key, value , expireSeconds , TimeUnit.SECONDS);
@Override
public void setKey(String key, String value) {
ValueOperations<String, String> ops = template.opsForValue();
ops.set(key,value);
}
存值设置值失效时间:
@Override
public void setKey(String key, String value, long timeOut, TimeUnit unit) {
ValueOperations<String, String> ops = template.opsForValue();
ops.set(key,value,timeOut,unit);
}
3、setnx锁
如果key不存在设置value值,返回true,存在返回false;
并发锁、原子操作、幂等性
// 设置redis锁
String key = "worship_packet_open_lock:" + phone + "_" + id;
if (!cacheService.setnx(key, userId.toString())) {
throw new BusinessException(ErrorStatus.ILLEGAL_ARGUMENT, "正在拆红包,请勿重复点击");
}
@Override
public boolean setnx(String key, String value) {
Boolean aBoolean = template.opsForValue().setIfAbsent(key, value);
if (aBoolean) {
template.opsForValue().set(key,value,60,TimeUnit.SECONDS);
}
return aBoolean;
}
4、根据key删除redis值
cacheService.delKey ( key );
@Override
public void delKey(String key) {
if (hasKey(key)) {
template.delete(key);
}
}
5、自增键
Long count = cacheService.getRedisSequence();
@Autowired
private RedisAtomicLong redisAtomicLong ;
@Override
public long getRedisSequence(){
long sequence = 00001L;
try {
if(redisAtomicLong.get() == 00001){
redisAtomicLong.getAndSet(00001L);
}
sequence = redisAtomicLong.incrementAndGet();
}catch(Exception e){
log.error("Failed to get sequence;自增失败" ,e);
}
return sequence ;
}
6、键每次新增次数
Long count = cacheService.boundValueOps(key + phone, 1);
@Override
public Long boundValueOps(String key, Integer num) {
return template.boundValueOps(key).increment(num);
}
7、设置过期时间
cacheService.expire(key , 1L , TimeUnit.HOURS );
//指定缓存失效时间
@Override
public boolean expire(String key, long time, TimeUnit unit) {
try {
if (time > 0) {
template.expire(key, time, unit);
}
return true;
} catch (Exception e) {
log.error(e.getMessage(),e);
return false;
}
}
8、判断key是否存在
Boolean exist = cacheService.hasKey(key);
@Override
public Boolean hasKey(String key) {
return template.hasKey(key);
}
9、根据key计算redis中list长度
Long size = cacheService.maxlistsize(limitSendRedisKey);
@Override
public Long maxlistsize(String key) {
ListOperations<String, String> opsForList = template.opsForList();
return opsForList.size(key);
}
10、list类型添加元素两种方式
LPush方法添加元素(从头部加入元素,先进后出、栈)
cacheService.leftPush(limitSendRedisKey, String.valueOf(redisTimeValue));
@Override
public Long leftPush(String key, String value) {
ListOperations<String, String> opsForList = template.opsForList();
return opsForList.leftPush(key,value);
}
list类型rPush方法添加元素(从尾部加入元素,先进先出、队列)
opsForList.rightPush(key,value);
11、删除list集合元素
lPop:从list的头部删除元素
//rPop:从list的尾部删除元素,并返回删除元素
cacheService.rightPop(limitSendRedisKey)
@Override
public String rightPop(String pop) {
ListOperations<String, String> opsForList = template.opsForList();
return opsForList.rightPop(pop);
}
12、获取key当前剩余过期时间
long expire = cacheService.getExpire(countKey, timeUnit);
@Override
public long getExpire(String key, TimeUnit unit) {
return template.getExpire(key, unit);
}
13、通过key获取原子数据
int optValueAtomic = cacheService.getOptValueAtomic(key);
@Override
public int getOptValueAtomic(String key) {
int count = 0;
if(Boolean.TRUE.equals(template.hasKey(key))){
count = Integer.valueOf(getValue(key));
}
return count;
}
14、对数据进行加减原子性操作
*@param key redis key
* @param isAdd 是否是新增
* @param changeValue 需要更该的参数(加几减几)
cacheService.optAtomic(key , true , count );
@Override
public int optAtomic(String key, boolean isAdd, Integer changeValue) {
//通过key获取原子数据
int optValueAtomic = getOptValueAtomic(key);
RedisAtomicInteger counter;
if(!isAdd && optValueAtomic < changeValue){
throw new BusinessException(ErrorStatus.ILLEGAL_DATA,"库存已不足");
}
if(Boolean.TRUE.equals(template.hasKey(key))){
return isAdd ? Integer.valueOf(template.opsForValue().increment(key, changeValue).toString()) :Integer.valueOf(template.opsForValue().increment(key, -changeValue).toString());
}else{
counter = new RedisAtomicInteger(key, Objects.requireNonNull(template.getConnectionFactory()),optValueAtomic);
return isAdd ? counter.addAndGet(changeValue) : counter.addAndGet(-changeValue);
}
}