package com.ld.igds.util;
|
|
import lombok.extern.slf4j.Slf4j;
|
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.data.redis.core.RedisTemplate;
|
import org.springframework.data.redis.core.StringRedisTemplate;
|
import org.springframework.stereotype.Service;
|
import org.springframework.util.CollectionUtils;
|
|
import java.util.Set;
|
import java.util.concurrent.TimeUnit;
|
|
/**
|
* Redis使用服务封装
|
*
|
* @author Andy
|
*/
|
@Service(RedisUtil.BEAN_ID)
|
@Slf4j
|
public class RedisUtil {
|
|
public static final String BEAN_ID = "base.redisUtil";
|
|
@Autowired
|
private StringRedisTemplate stringRedisTemplate;
|
@Autowired
|
private RedisTemplate<String, Object> redisTemplate;
|
|
|
// ============================String=============================//
|
|
/**
|
* 普通缓存获取
|
* @param key 键
|
* @return 值
|
*/
|
public Object get(String key) {
|
return key == null ? null : redisTemplate.opsForValue().get(key);
|
}
|
|
/**
|
* 普通缓存放入
|
*
|
* @param key 键
|
* @param value 值
|
* @return true成功 false失败
|
*/
|
public boolean set(String key, Object value) {
|
try {
|
redisTemplate.opsForValue().set(key, value);
|
return true;
|
} catch (Exception e) {
|
log.error("添加缓存异常,KEY={},异常原因:{}", key, e);
|
return false;
|
}
|
|
}
|
|
/**
|
* 普通缓存放入并设置时间
|
*
|
* @param key 键
|
* @param value 值
|
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
|
* @return true成功 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) {
|
log.error("添加缓存异常,KEY={},异常原因:{}", key, e);
|
return false;
|
}
|
}
|
|
/**
|
* 递增
|
*
|
* @param key 键
|
* @param delta 要增加几(大于0)
|
* @return
|
*/
|
public long incr(String key, long delta) {
|
if (delta < 0) {
|
throw new RuntimeException("递增因子必须大于0");
|
}
|
return redisTemplate.opsForValue().increment(key, delta);
|
}
|
|
/**
|
* 递减
|
*
|
* @param key 键
|
* @param delta 要减少几(小于0)
|
* @return
|
*/
|
public long decr(String key, long delta) {
|
if (delta < 0) {
|
throw new RuntimeException("递减因子必须大于0");
|
}
|
return redisTemplate.opsForValue().increment(key, -delta);
|
}
|
|
/**
|
* 删除缓存
|
*
|
* @param key 可以传一个值 或多个
|
*/
|
@SuppressWarnings("unchecked")
|
public void del(String... key) {
|
if (key != null && key.length > 0) {
|
if (key.length == 1) {
|
redisTemplate.delete(key[0]);
|
} else {
|
redisTemplate.delete(CollectionUtils.arrayToList(key));
|
}
|
}
|
}
|
|
/**
|
* 根据缓存前缀获取所有的KEY信息
|
*
|
* @param pattern 缓存前缀,不需要添加通配符
|
* @return
|
*/
|
public Set<String> keys(String pattern) {
|
return redisTemplate.keys(pattern + "*");
|
}
|
}
|