package com.example.api.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtil {
private static final Long SUCCESS = 1L;
@Autowired
private RedisTemplate redisTemplate;
public void expire(String key, long time) {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
} else {
throw MyExceptionUtils.mxe("设置的时间不能为0或者小于0!!");
}
}
public Boolean existsKey(String key) {
return redisTemplate.hasKey(key);
}
public DataType typeKey(String key) {
return redisTemplate.type(key);
}
public Boolean deleteKey(String key) {
try {
redisTemplate.delete(key);
return true;
} catch (Exception ex) {
throw MyExceptionUtils.mxe("删除失败!", ex);
}
}
public Boolean deleteKey(Collection<String> keys) {
try {
redisTemplate.delete(keys);
return true;
} catch (Exception ex) {
throw MyExceptionUtils.mxe("删除失败!", ex);
}
}
public Boolean setString(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception ex) {
throw MyExceptionUtils.mxe("插入缓存失败!", ex);
}
}
public Object getString(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
public boolean setString(String key, Object value, long time) {
try {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
return true;
} catch (Exception ex) {
throw MyExceptionUtils.mxe("插入缓存失败!", ex);
}
}
public Boolean setHash(String key, Object hk, Object hv, long time) {
redisTemplate.opsForHash().put(key, hk, hv);
redisTemplate.expire(key, time, TimeUnit.SECONDS);
return true;
}
public Boolean setHash(String key, Map map, long time) {
redisTemplate.opsForHash().putAll(key, map);
redisTemplate.expire(key, time, TimeUnit.SECONDS);
return true;
}
public Object getHash(String key, String hk) {
return key == null ? null : (hk == null ? null : redisTemplate.opsForHash().get(key, hk));
}
public Long hincrease(String key, String hk, long l) {
return redisTemplate.opsForHash().increment(key, hk, l);
}
public Boolean setList(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception ex) {
throw MyExceptionUtils.mxe("插入List缓存失败!", ex);
}
}
public Boolean setList(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForList().rightPush(key, value);
expire(key, time);
return true;
}
return false;
} catch (Exception ex) {
throw MyExceptionUtils.mxe("插入List缓存失败!", ex);
}
}
public Boolean setListAll(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForList().rightPushAll(key, value);
this.expire(key, time);
return true;
}
return false;
} catch (Exception ex) {
throw MyExceptionUtils.mxe("插入List缓存失败!", ex);
}
}
public List<Object> getList(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception ex) {
throw MyExceptionUtils.mxe("获取缓存List中的内容失败了!", ex);
}
}
public long deleteListIndex(String key, long count, Object value) {
try {
return redisTemplate.opsForList().remove(key, count, value);
} catch (Exception ex) {
throw MyExceptionUtils.mxe("删除List中的内容失败了!", ex);
}
}
public long getListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception ex) {
throw MyExceptionUtils.mxe("获取List长度失败", ex);
}
}
public void isContainsKey(String key, HashSet o) {
redisTemplate.opsForSet().isMember(key, o);
}
public boolean tryLock(String lockKey, String requestId, int expireTime,long waitTimeout) {
long nanoTime = System.nanoTime();
try{
String script = "if redis.call('setNx',KEYS[1],ARGV[1]) then if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('expire',KEYS[1],ARGV[2]) else return 0 end end";
int count = 0;
do{
RedisScript<String> redisScript = new DefaultRedisScript<>(script, String.class);
Object result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey),requestId,expireTime);
if(SUCCESS.equals(result)) {
return true;
}
Thread.sleep(500L);
count++;
}while ((System.nanoTime() - nanoTime) < TimeUnit.MILLISECONDS.toNanos(waitTimeout));
}catch(Exception e){
System.out.println("尝试获取分布式锁-key[{}]异常"+lockKey);
}
return false;
}
public boolean releaseLock(String lockKey, String requestId) {
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
RedisScript<String> redisScript = new DefaultRedisScript<>(script, String.class);
Object result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey), requestId);
if (SUCCESS.equals(result)) {
return true;
}
return false;
}
}
RedisController
@RestController
@RequestMapping(value="/redis", produces = "application/json; charset=UTF-8")
public class RedisController {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private RedisUtil redisUtil;
@RequestMapping( "/set")
public String setUserName( String name) {
redisTemplate.opsForValue().set("1", name);
return "succees";
}
@RequestMapping( "/get")
public String getUserName( String key) {
return redisTemplate.opsForValue().get(key).toString();
}
@RequestMapping( "/delete")
public Boolean deleteKey(String key) {
return redisUtil.deleteKey(key);
}
@RequestMapping( "/newset")
public Boolean newSetName(String name) {
return redisUtil.setString("2",name);
}
}