概述
最近项目使用到Redis作为缓存,以下是用redis一些使用,做的一次随笔记载。
使用环境:spring boot 2.1.X、Redis 5.0.X(服务端)、spring-boot-starter-data-redis
spring boot集成Redis
pom文件引用
默认使用lettuce连接池
<!--集成Redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<optional>true</optional>
</dependency>
<!--redis连接池 start-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<!--redis连接池 end-->
配置文件配置,使用Redis 单机模式
spring:
redis:
#使用数据库,默认:0
database: 1
host: 192.168.2.102
port: 6379
#超时时间ms
timeout: 1000
lettuce:
pool:
#连接池最大连接数(使用负值表示没有限制)默认:8
max-active: 200
#连接池最大阻塞等待时间(使用负值表示没有限制)默认:-1
max-wait: -1ms
#最大空闲连接数,默认:8
max-idle: 8
#最小空闲连接数,默认:0
min-idle: 4
#回收线程间隔毫秒数
time-between-eviction-runs: 1
RedisTemplate 配置类配置
该配置主要是配置默认的序列化方式:JdkSerializationRedisSerializer,默认的序列化会给所有的key,value的原始字符前,都加了一串字符(例如:xACxEDx00),不具备可读性
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String,Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory){
RedisTemplate<String,Object>redisTemplate=new RedisTemplate<>();
redisTemplate.setConnectionFactory(lettuceConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
Jackson2JsonRedisSerializer<Object> serializer=new Jackson2JsonRedisSerializer<Object>(Object.class);
redisTemplate.setValueSerializer(serializer);
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(serializer);
return redisTemplate;
}
}
RedisService接口
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @Description: Redis接口
* @Autoer: XingWeiLei
* @Date: 2020/07/30 13:19
*/
public interface RedisService {
/**
* @author:XingWL
* @description:string,设置<K,V>缓存
* @date: 2020/7/30 13:23
*/
void put(String key,String value);
/**
* @author:XingWL
* @description:string,设置<K,V>缓存,过期时间(毫秒)
* @date: 2020/7/30 13:37
*/
void put(String key,String value,Long seconds);
/**
* @author:XingWL
* @description:string,获取value
* @date: 2020/7/30 13:39
*/
String get(String key);
/**
* @author:XingWL
* @description:string,删除key
* @date: 2020/7/30 13:51
*/
boolean removeStr(String key);
/**
* @author:XingWL
* @description:string,如果key不存在则设置值
* @date: 2020/7/30 14:45
*/
boolean setnx(String key,String value);
/**
* @author:XingWL
* @description:string,如果存在则设置
* @date: 2020/7/30 14:47
*/
boolean setex(String key,String value);
/**
* @author:XingWL
* @description:list,列表大小
* @date: 2020/8/3 18:14
*/
Long listSize(String key);
/**
* @author:XingWL
* @description:list,获取列表中第一个元素,并删除
* @date: 2020/8/3 9:00
*/
Object leftPop(String key);
/**
* @author:XingWL
* @description:list,右添加新元素
* @date: 2020/7/30 18:00
*/
Long rightPush(String key,Object value);
/**
* @author:XingWL
* @description:list,右添加集合
* @date: 2020/7/30 18:00
*/
Long rightPushAll(String key, Collection<Object> values);
/**
* @author:XingWL
* @description:list,获取列表
* @param start 起始位置:0
* @param end 终止位置:(包含end下标的元素;-1 标识获取key下所有元素)
* @date: 2020/7/30 18:39
*/
List<Object> range(String key,long start,long end);
/**
* @author:XingWL
* @description:list删除列表元素
* @param count:rvalue 元素出现列表出现次数,count=0删除所有;count>0 从左开始删除;count<0 从右删除
* @date: 2020/8/3 9:41
*/
Long remove(String key,long count,String rvalue);
/**
* @author:XingWL
* @description:hash,添加元素
* @date: 2020/7/30 19:52
*/
void hashPut(String key,String hKey,Object hValue);
/**
* @author:XingWL
* @description:hash,添加多元素
* @param map : k: HK,v:HV
* @date: 2020/7/31 8:37
*/
void hashPutAll(String key, Map<String,Object>map);
/**
* @author:XingWL
* @description:hash,获取HK
* @date: 2020/7/31 8:39
* @return
*/
Set<Object> hKeys(String key);
/**
* @author:XingWL
* @description:hash,获取HV
* @date: 2020/7/31 8:40
*/
Object hGet(String key,String hKey);
/**
* @author:XingWL
* @description:hash,判断HK是否存在
* @date: 2020/7/31 8:42
*/
boolean hasKey(String key,String hKey);
/**
* @author:XingWL
* @description:hash,批量获取HV
* @date: 2020/7/31 8:45
*/
List<Object> multGet(String key,Collection<String> hKeys);
/**
* @author:XingWL
* @description:(Redis>=2.4)set,添加元素
* @date: 2020/7/31 8:50
*/
Long setAdd(String key,Object... values);
/**
* @author:XingWL
* @description:set,删除值
* @date: 2020/7/31 8:55
*/
Long setRemove(String key,Object... values);
/**
* @author:XingWL
* @description:set,获取values
* @date: 2020/7/31 8:56
*/
Set<Object> members(String key);
/**
* @author:XingWL
* @description:set,判断key是否包含value
* @date: 2020/7/31 8:58
*/
boolean isMember(String key,Object value);
/**
* @author:XingWL
* @description:set,获取集合随机一个值,并删除
* @date: 2020/8/4 13:57
*/
Object setPop(String key);
/**
* @author:XingWL
* @description:set,获取集合随机count数量的值,并删除
* @date: 2020/8/4 13:57
*/
List<Object> setPops(String key,long count);
/**
* @author:XingWL
* @description:set,集合大小
* @date: 2020/8/4 15:49
*/
Long setSize(String key);
/**
* @author:XingWL
* @description:获取锁
* @date: 2020/7/31 9:29
*/
boolean getLock(String lockKey,String lockValue,int expireTime);
/**
* @author:XingWL
* @description:解锁
* @date: 2020/7/31 9:32
*/
boolean releaseLock(String lockKey,String lockValue);
}
RedisServiceImpl实现类
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
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.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
/**
* @Description: Redis方法实现类
* @Autoer: XingWeiLei
* @Date: 2020/07/30 13:23
*/
@Slf4j
@Component
public class RedisServiceImpl implements RedisService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
private static final Long SUCCESS = 1L;
private void check() throws NullPointerException {
if (redisTemplate == null) {
throw new NullPointerException("RedisTemplate Is NULL");
}
}
/**
* @author:XingWL
* @description:string,设置<K,V>缓存
* @date: 2020/7/30 13:23
*/
@Override
public void put(String key, String value) {
check();
redisTemplate.opsForValue().set(key, value);
}
/**
* @author:XingWL
* @description:string,设置<K,V>缓存,过期时间(毫秒)
* @date: 2020/7/30 13:37
*/
@Override
public void put(String key, String value, Long seconds) {
check();
redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.MILLISECONDS);
}
/**
* @author:XingWL
* @description:string,获取value
* @date: 2020/7/30 13:39
*/
@Override
public String get(String key) {
check();
boolean flag = redisTemplate.hasKey(key);
if (flag) {
return redisTemplate.opsForValue().get(key).toString();
}
return null;
}
/**
* @author:XingWL
* @description:string,删除key
* @date: 2020/7/30 13:51
*/
@Override
public boolean removeStr(String key) {
check();
return redisTemplate.delete(key);
}
/**
* @author:XingWL
* @description:string,如果key不存在则设置值
* @date: 2020/7/30 14:45
*/
@Override
public boolean setnx(String key, String value) {
check();
return redisTemplate.opsForValue().setIfAbsent(key, value);
}
/**
* @author:XingWL
* @description:string,如果存在则设置
* @date: 2020/7/30 14:47
*/
@Override
public boolean setex(String key, String value) {
check();
return redisTemplate.opsForValue().setIfPresent(key, value);
}
@Override
public Long listSize(String key) {
check();
return redisTemplate.opsForList().size(key);
}
@Override
public Object leftPop(String key) {
check();
return redisTemplate.opsForList().leftPop(key);
}
/**
* @author:XingWL
* @description:list,右添加新元素
* @date: 2020/7/30 18:00
*/
@Override
public Long rightPush(String key, Object value) {
check();
return redisTemplate.opsForList().rightPush(key, value);
}
/**
* @author:XingWL
* @description:list,右添加集合
* @date: 2020/7/30 18:00
*/
@Override
public Long rightPushAll(String key, Collection<Object> values) {
check();
return redisTemplate.opsForList().rightPushAll(key, values);
}
/**
* @param start 起始位置:0
* @param end 终止位置:(包含end下标的元素;-1 标识获取key下所有元素)
* @author:XingWL
* @description:list,获取列表
* @date: 2020/7/30 18:39
*/
@Override
public List<Object> range(String key, long start, long end) {
check();
return redisTemplate.opsForList().range(key, start, end);
}
@Override
public Long remove(String key, long count, String rvalue) {
check();
return redisTemplate.opsForList().remove(key,count,rvalue);
}
/**
* @author:XingWL
* @description:hash,添加元素
* @date: 2020/7/30 19:52
*/
@Override
public void hashPut(String key, String hKey, Object hValue) {
check();
redisTemplate.opsForHash().put(key, hKey, hValue);
}
/**
* @param map : k: HK,v:HV
* @author:XingWL
* @description:hash,添加多元素
* @date: 2020/7/31 8:37
*/
@Override
public void hashPutAll(String key, Map<String, Object> map) {
check();
redisTemplate.opsForHash().putAll(key, map);
}
/**
* @return
* @author:XingWL
* @description:hash,获取HK
* @date: 2020/7/31 8:39
*/
@Override
public Set<Object> hKeys(String key) {
check();
return redisTemplate.opsForHash().keys(key);
}
/**
* @author:XingWL
* @description:hash,获取HV
* @date: 2020/7/31 8:40
*/
@Override
public Object hGet(String key, String hKey) {
check();
return redisTemplate.opsForHash().get(key, hKey);
}
/**
* @author:XingWL
* @description:hash,判断HK是否存在
* @date: 2020/7/31 8:42
*/
@Override
public boolean hasKey(String key, String hKey) {
check();
return redisTemplate.opsForHash().hasKey(key, hKey);
}
/**
* @author:XingWL
* @description:hash,批量获取HV
* @date: 2020/7/31 8:45
*/
@Override
public List<Object> multGet(String key, Collection<String> hKeys) {
check();
return redisTemplate.opsForHash().multiGet(key, Collections.singletonList(hKeys));
}
/**
* @author:XingWL
* @description:(Redis>=2.4)set,添加元素
* @date: 2020/7/31 8:50
*/
@Override
public Long setAdd(String key, Object... values) {
check();
return redisTemplate.opsForSet().add(key, values);
}
/**
* @author:XingWL
* @description:set,删除值
* @date: 2020/7/31 8:55
*/
@Override
public Long setRemove(String key, Object... values) {
check();
return redisTemplate.opsForSet().remove(key, values);
}
/**
* @author:XingWL
* @description:set,获取values
* @date: 2020/7/31 8:56
*/
@Override
public Set<Object> members(String key) {
check();
return redisTemplate.opsForSet().members(key);
}
/**
* @author:XingWL
* @description:set,判断key是否包含value
* @date: 2020/7/31 8:58
*/
@Override
public boolean isMember(String key, Object value) {
check();
return redisTemplate.opsForSet().isMember(key, value);
}
@Override
public Object setPop(String key) {
check();
return redisTemplate.opsForSet().pop(key);
}
@Override
public List<Object> setPops(String key, long count) {
check();
return redisTemplate.opsForSet().pop(key,count);
}
@Override
public Long setSize(String key) {
check();
return redisTemplate.opsForSet().size(key);
}
/**
* @author:XingWL
* @description:获取锁
* @param expireTime :s
* @date: 2020/7/31 9:29
*/
@Override
public boolean getLock(String lockKey, String lockValue, int expireTime) {
boolean ret = false;
try {
check();
String script = "if redis.call('setNx',KEYS[1],ARGV[1])==1 then if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('expire',KEYS[1],ARGV[2]) else return 0 end end";
RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
Object result = redisTemplate
.execute(redisScript, Collections.singletonList(lockKey), lockValue, expireTime);
if (SUCCESS.equals(result)) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
log.error("Redis获取Lock失败!");
}
return ret;
}
/**
* @author:XingWL
* @description:解锁
* @date: 2020/7/31 9:32
*/
@Override
public boolean releaseLock(String lockKey, String lockValue) {
try {
check();
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
Object result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey),lockValue);
if(SUCCESS.equals(result)) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
log.error("Redis释放Lock失败!");
}
return false;
}
}
以上是Redis集成单机版简单使用,后续相关集群使用方式。。。。
替换连接为Jedis
添加依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
添加配置
#使用单个redis=redis,redis集群=redisCluster
srping.redis.type=redis
#单个redis
spring.redis.host=ip
spring.redis.port=6379
spring.redis.password=xxx
#可用连接实例的最大数目,默认值为8;
#如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
spring.redis.maxActive=1000
# 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
spring.redis.maxIdle=20
#等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
spring.redis.maxWait=10000
#在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
spring.redis.testOnBorrow=true
spring.redis.testOnReturn=true
spring.redis.timeOut=3000
#redis超时时间 1*1*60*60
spring.redis.redisExpire=3600
#redis集群配置
spring.redis.pool.nodes=ip:port1,ip:port2,ip:port3
spring.redis.pool.timeOut=3000
#返回值的超时时间
spring.redis.pool.soTimeOut=5000
spring.redis.pool.maxActive=1024
spring.redis.pool.maxIdle=200
spring.redis.pool.maxWait=10000
spring.redis.pool.maxAttempts=5
spring.redis.pool.testOnBorrow=true
spring.redis.pool.password=ganinfo
spring.redis.pool.expireSeconds=3600
RedisFactory用于切换jedis使用方式(单机、集群)
@Component
public class RedisFactory {
@Autowired
private List<RedisService> redisServiceFactorys;
@Value("${srping.redis.type}")
private String redisType;
public RedisService getRedis() {
RedisService brandFactory = null;
for (RedisService tmpFactory : redisServiceFactorys) {
if (tmpFactory.getSupportType().equals(redisType)) {
brandFactory = tmpFactory;
break;
}
}
return brandFactory;
}
}
单机
import java.util.List;
import java.util.Map;
/**
* @author:XingWL
* @version V1.0
* @ClassName: RedisDao
* @Description: redis接口
* @date 2017年11月23日 下午3:55:53
*/
public interface RedisService {
/**
* 设置缓存
*
* @param key 缓存key
* @param value 缓存value
*/
void set(String key, String value);
/**
* 设置缓存,并且自己指定过期时间
*
* @param key
* @param value
* @param expireTime 过期时间
*/
void setWithExpireTime(String key, String value, int expireTime);
/**
* 设置缓存,并且由配置文件指定过期时间
*
* @param key
* @param value
*/
void setWithExpireTime(String key, String value);
/**
* 获取指定key的缓存
*
* @param key
*/
String get(String key);
/**
* 删除指定key的缓存
*
* @param key
*/
void del(String key);
void delString(String key);
/**
* 判断key是否存在
*
* @param key
*/
Boolean exists(String key);
/**
* 缓存Bean类型
*
* @param key
* @param bean
*/
<T> void setBean(String key, Object bean);
/**
* 获取Bean类型
*
* @param key
*/
<T> T getBean(String key);
/**
* 缓存List类型
*
* @param key
* @param list
*/
<T> void setList(String key, List<T> list);
/**
* 获取List类型
*
* @param key
*/
<T> List<T> getList(String key);
/**
* 用户登录
*
* @param userCode
*/
String login(String userCode);
/**
* 用户校验
*
* @param accessToken
*/
void validate(String accessToken);
/**
* 用户退出
*
* @param accessToken
*/
void logout(String accessToken);
/**
* 获取用户code
*
* @param accessToken
*/
String getUserId(String accessToken);
String getSupportType();
// String setnx();
/**
* @author:XingWL
* @description:查询缓存数据量
* @date: 2018/4/24 14:02
*/
long getValue(String key);
/**
* @author:XingWL
* @description:获取分布式锁
* @date: 2018/5/11 13:46
*/
String setLock(String lockKey, String requestId, int expireTime);
/**
* @author:XingWL
* @description:释放分布式锁
* @date: 2018/5/11 14:03
*/
Object releaseLock(String lockKey, String requestId);
/**
* @author:XingWL
* @description:获取字符串
* @date: 2018/5/30 19:30
*/
String getString(String key);
/**
* @author:XingWL
* @description:批量删除
* @date: 2018/9/14 16:54
*/
void dels(String pattern );
/**
* @author:XingWL
* @description:根据key查询hash
* @date: 2018/12/5 18:26
* @param: key
* @return: Map<String, String>
*/
Map<String, String> getHash(String key);
/**
* @author:XingWL
* @description:哈希-存值
* @date: 2018/11/20 15:29
*/
void hashSetMapString(String key, Map<String, String> map);
/**
* @author:XingWL
* @description:哈希-设置一个键值对(不存在,则创建;否则,修改)
* @date: 2018/11/20 16:21
*/
void hashSetOneString(String key, String field, String value);
/**
* @author:XingWL
* @description:哈希-判断该map中是否存在该field
* @date: 2018/11/20 15:31
*/
boolean hashExistFieldString(String key, String field);
/**
* @author:XingWL
* @description:哈希-删除map中指定key
* @date: 2018/11/20 15:37
*/
void hashDelFieldString(String key, String field);
/**
* @author:XingWL
* @description:哈希-获取指定map-key的值
* @date: 2018/11/20 15:37
*/
String hashGetValueString(String key, String field);
}
RedisServiceImpl
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author shuyu.wang
* @version V1.0
* @ClassName: RedisDaoImpl
* @Description: TODO
* @date 2017年10月19日 下午2:54:39
*/
@Service
@RefreshScope
public class RedisServiceImpl implements RedisService {
private Logger logger = Logger.getLogger(RedisServiceImpl.class);
@Value("${spring.redis.host}")
private String ip;
@Value("${spring.redis.port}")
private Integer port;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.maxActive}")
private Integer maxActive;
@Value("${spring.redis.maxIdle}")
private Integer maxIdle;
@Value("${spring.redis.maxWait}")
private Long maxWait;
@Value("${spring.redis.testOnBorrow}")
private Boolean testOnBorrow;
@Value("${spring.redis.testOnReturn}")
private Boolean testOnReturn;
@Value("${spring.redis.timeOut}")
private Integer timeOut;
@Value("${spring.redis.redisExpire}")
private int redisExpire;
private static final String SET_IF_NOT_EXIST = "NX";
private static final String SET_WITH_EXPIRE_TIME = "PX";
private static final String VIRTUAL_COURSE_PREX = "lc_vc_";
@Value("${spring.redis.type:redis}")
private String redisType;
/**
* 非切片链接池
*/
private JedisPool jedisPool;
/**
* 在多线程环境同步初始化
*/
private void poolInit() {
if (!"redis".equals(redisType)) {
return;
}
if (jedisPool == null) {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(maxActive);
config.setMaxIdle(maxIdle);
config.setMaxWaitMillis(maxWait);
config.setTestOnBorrow(testOnBorrow);
config.setTestOnReturn(testOnReturn);
jedisPool = new JedisPool(config, ip, port, timeOut, password);
logger.info("初始化redis连接池");
}
}
private String buildKey(String key) {
return VIRTUAL_COURSE_PREX + key;
}
@Override
public void set(String key, String param) {
String bKey = buildKey(key);
Jedis jedis = null;
try {
if (jedisPool == null) {
poolInit();
}
if (jedisPool != null) {
jedis = jedisPool.getResource();
jedis.set(bKey.getBytes(), SerializeUtil.serialize(param));
}
} catch (Exception e) {
logger.error("redis连接异常");
e.printStackTrace();
// 释放jedis对象
jedisPool.returnBrokenResource(jedis);
} finally {
// 返还连接池
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
}
@Override
public void setWithExpireTime(String key, String value, int expireTime) {
Jedis jedis = null;
try {
if (jedisPool == null) {
poolInit();
}
if (jedisPool != null) {
jedis = jedisPool.getResource();
jedis.setex(buildKey(key), expireTime, value);
}
} catch (Exception e) {
logger.error("redis连接异常");
e.printStackTrace();
// 释放jedis对象
jedisPool.returnBrokenResource(jedis);
} finally {
// 返还连接池
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
}
@Override
public void setWithExpireTime(String key, String value) {
Jedis jedis = null;
try {
if (jedisPool == null) {
poolInit();
}
if (jedisPool != null) {
jedis = jedisPool.getResource();
logger.info("获取redis连接");
jedis.setex(buildKey(key), redisExpire, value);
}
} catch (Exception e) {
logger.error("redis连接异常");
e.printStackTrace();
// 释放jedis对象
jedisPool.returnBrokenResource(jedis);
} finally {
// 返还连接池
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
}
@Override
public String get(String key) {
String bKey = buildKey(key);
String retru = null;
Jedis jedis = null;
try {
if (jedisPool == null) {
poolInit();
}
if (jedisPool != null) {
jedis = jedisPool.getResource();
logger.info("获取redis连接");
if (jedis == null || !jedis.exists(bKey.getBytes())) {
return null;
}
byte[] in = jedis.get(bKey.getBytes());
retru = SerializeUtil.unserialize(in).toString();
}
} catch (Exception e) {
logger.error("redis连接异常");
e.printStackTrace();
// 释放jedis对象
jedisPool.returnBrokenResource(jedis);
} finally {
// 返还连接池
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
return retru;
}
@Override
public void del(String key) {
String bKey = buildKey(key);
Jedis jedis = null;
try {
if (jedisPool == null) {
poolInit();
}
if (jedisPool != null) {
jedis = jedisPool.getResource();
if (jedis != null && jedis.exists(bKey.getBytes())) {
jedis.del(bKey.getBytes());
}
}
} catch (Exception e) {
logger.error("redis连接异常");
e.printStackTrace();
// 释放jedis对象
jedisPool.returnBrokenResource(jedis);
} finally {
// 返还连接池
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
}
@Override
public void delString(String key) {
Jedis jedis = null;
try {
if (jedisPool == null) {
poolInit();
}
if (jedisPool != null) {
jedis = jedisPool.getResource();
if (jedis != null && jedis.exists(key)) {
jedis.del(key);
}
}
} catch (Exception e) {
logger.error("redis连接异常");
e.printStackTrace();
// 释放jedis对象
jedisPool.returnBrokenResource(jedis);
} finally {
// 返还连接池
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
}
@Override
public Boolean exists(String key) {
String bKey = buildKey(key);
Jedis jedis = null;
boolean flag = false;
try {
if (jedisPool == null) {
poolInit();
}
if (jedisPool != null) {
jedis = jedisPool.getResource();
if (jedis != null && jedis.exists(bKey.getBytes())) {
flag = true;
}
}
} catch (Exception e) {
logger.error("redis连接异常");
e.printStackTrace();
// 释放jedis对象
jedisPool.returnBrokenResource(jedis);
} finally {
// 返还连接池
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
return flag;
}
/**
* @param key
* @param bean
*/
@Override
public <T> void setBean(String key, Object bean) {
String bKey = buildKey(key);
Jedis jedis = null;
try {
if (jedisPool == null) {
poolInit();
}
if (jedisPool != null) {
jedis = jedisPool.getResource();
jedis.set(bKey.getBytes(), SerializeUtil.serialize(bean));
}
} catch (Exception e) {
logger.error("redis连接异常");
e.printStackTrace();
// 释放jedis对象
jedisPool.returnBrokenResource(jedis);
} finally {
// 返还连接池
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
}
@Override
public <T> T getBean(String key) {
String bKey = buildKey(key);
T bean = null;
Jedis jedis = null;
try {
if (jedisPool == null) {
poolInit();
}
if (jedisPool != null) {
jedis = jedisPool.getResource();
if (jedis == null || !jedis.exists(bKey.getBytes())) {
return null;
}
byte[] in = jedis.get(bKey.getBytes());
bean = (T) SerializeUtil.unserialize(in);
}
} catch (Exception e) {
logger.error("redis连接异常");
e.printStackTrace();
// 释放jedis对象
jedisPool.returnBrokenResource(jedis);
} finally {
// 返还连接池
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
return bean;
}
/**
* @param key
* @param list
*/
@Override
public <T> void setList(String key, List<T> list) {
String bKey = buildKey(key);
Jedis jedis = null;
try {
if (jedisPool == null) {
poolInit();
}
if (jedisPool != null) {
jedis = jedisPool.getResource();
jedis.set(bKey.getBytes(), SerializeUtil.serialize(list));
}
} catch (Exception e) {
e.printStackTrace();
// 释放jedis对象
jedisPool.returnBrokenResource(jedis);
} finally {
// 返还连接池
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
}
/**
* @param key
* @return list
*/
@Override
public <T> List<T> getList(String key) {
Jedis jedis = null;
String bKey = buildKey(key);
List<T> list = null;
try {
if (jedisPool == null) {
poolInit();
}
if (jedisPool != null) {
jedis = jedisPool.getResource();
if (jedis == null || !jedis.exists(bKey.getBytes())) {
return null;
}
byte[] in = jedis.get(bKey.getBytes());
list = (List<T>) SerializeUtil.unserialize(in);
}
} catch (Exception e) {
logger.error("redis连接异常");
e.printStackTrace();
// 释放jedis对象
jedisPool.returnBrokenResource(jedis);
} finally {
// 返还连接池
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
return list;
}
/*
* (non-Javadoc)
*
* @see com.hc.redis.dao.RedisDao#login(java.lang.String, int)
*/
@Override
public String login(String userId) {
logger.info("用户登录");
String accessToken = UUIDUtil.creatUUID();
Jedis jedis = null;
try {
if (jedisPool == null) {
poolInit();
}
if (jedisPool != null) {
jedis = jedisPool.getResource();
if (jedis != null && !jedis.exists(userId)) {
// token生产规则自定义ֵ
jedis.setex(accessToken, redisExpire, userId);
jedis.setex(userId, redisExpire, accessToken);
} else if (jedis != null && jedis.exists(userId)) {
//销毁之前的token
String token = jedis.get(userId);
if (CommonUtil.isNotNullEmpty(token)) {
jedis.del(token);
}
jedis.del(userId);
//重新生成token
jedis.setex(accessToken, redisExpire, userId);
jedis.setex(userId, redisExpire, accessToken);
}
}
} catch (Exception e) {
logger.error("redis连接异常");
e.printStackTrace();
// 释放jedis对象
jedisPool.returnBrokenResource(jedis);
} finally {
// 返还连接池
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
return accessToken;
}
@Override
public void validate(String token) {
Jedis jedis = null;
try {
if (jedisPool == null) {
poolInit();
}
if (jedisPool != null) {
jedis = jedisPool.getResource();
if (jedis != null && jedis.exists(token)) {
//重新设置有效时间
String userId = this.getUserId(token);
jedis.expire(token, redisExpire);
jedis.expire(userId, redisExpire);
}
}
} catch (Exception e) {
logger.error("redis连接异常");
e.printStackTrace();
// 释放jedis对象
jedisPool.returnBrokenResource(jedis);
} finally {
// 返还连接池
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
}
@Override
public void logout(String token) {
Jedis jedis = null;
try {
if (jedisPool == null) {
poolInit();
}
if (jedisPool != null) {
jedis = jedisPool.getResource();
if (jedis != null && jedis.exists(token)) {
String userId = this.getUserId(token);
jedis.del(userId);
jedis.del(token);
}
}
} catch (Exception e) {
logger.error("redis连接异常");
e.printStackTrace();
// 释放jedis对象
jedisPool.returnBrokenResource(jedis);
} finally {
// 返还连接池
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
}
@Override
public String getUserId(String token) {
Jedis jedis = null;
String userId = null;
try {
if (jedisPool == null) {
poolInit();
}
if (jedisPool != null) {
jedis = jedisPool.getResource();
if (jedis != null && jedis.exists(token)) {
userId = jedis.get(token);
}
}
} catch (Exception e) {
logger.error("redis连接异常");
e.printStackTrace();
// 释放jedis对象
jedisPool.returnBrokenResource(jedis);
} finally {
// 返还连接池
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
return userId;
}
@Override
public String getSupportType() {
return "redis";
}
@Override
public long getValue(String key) {
Jedis jedis = null;
String count = null;
try {
if (jedisPool == null) {
poolInit();
}
if (jedisPool != null) {
jedis = jedisPool.getResource();
if (jedis != null && jedis.exists(key)) {
count = jedis.get(key);
} else {
return 0;
}
}
} catch (Exception e) {
logger.error("redis连接异常");
e.printStackTrace();
// 释放jedis对象
jedisPool.returnBrokenResource(jedis);
} finally {
// 返还连接池
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
return Long.valueOf(count);
}
@Override
public String setLock(String lockKey, String requestId, int expireTime) {
Jedis jedis = null;
String result = null;
try {
if (jedisPool == null) {
poolInit();
}
if (jedisPool != null) {
jedis = jedisPool.getResource();
if (jedis != null) {
result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
} else {
return result;
}
}
} catch (Exception e) {
logger.error("redis连接异常");
e.printStackTrace();
// 释放jedis对象
jedisPool.returnBrokenResource(jedis);
} finally {
// 返还连接池
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
return result;
}
@Override
public Object releaseLock(String lockKey, String requestId) {
Jedis jedis = null;
Object result = null;
try {
if (jedisPool == null) {
poolInit();
}
if (jedisPool != null) {
jedis = jedisPool.getResource();
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
if (jedis != null) {
result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
} else {
return result;
}
}
} catch (Exception e) {
logger.error("redis连接异常");
e.printStackTrace();
// 释放jedis对象
jedisPool.returnBrokenResource(jedis);
} finally {
// 返还连接池
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
return result;
}
@Override
public String getString(String key) {
Jedis jedis = null;
String count = null;
try {
if (jedisPool == null) {
poolInit();
}
if (jedisPool != null) {
jedis = jedisPool.getResource();
if (jedis != null && jedis.exists(key)) {
count = jedis.get(key);
} else {
return null;
}
}
} catch (Exception e) {
logger.error("redis连接异常");
e.printStackTrace();
// 释放jedis对象
jedisPool.returnBrokenResource(jedis);
} finally {
// 返还连接池
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
return count;
}
/**
* @author:XingWL
* @description:批量删除keys
* @date: 2018/10/17 15:57
*/
@Override
public void dels(String pattern) {
String bKey = buildKey(pattern);
Jedis jedis = null;
try {
Set<String> keys = null;
if (jedisPool == null) {
poolInit();
}
if (jedisPool != null) {
jedis = jedisPool.getResource();
if (jedis != null && CommonUtil.isNotNullEmpty(pattern)) {
keys = jedis.keys(bKey + "*");
if (keys != null) {
for (String key : keys) {
System.err.println(key);
jedis.del(key.getBytes());
}
}
}
}
} catch (Exception e) {
logger.error("redis连接异常");
e.printStackTrace();
// 释放jedis对象
jedisPool.returnBrokenResource(jedis);
} finally {
// 返还连接池
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
}
/**
* @param key
* @author:XingWL
* @description:根据key查询hash
* @date: 2018/12/5 18:26
* @param: null
* @return: null
*/
@Override
public Map<String, String> getHash(String key) {
Jedis jedis = null;
String count = null;
logger.error(">>>");
try {
if (jedisPool == null) {
poolInit();
}
if (jedisPool != null) {
jedis = jedisPool.getResource();
if (jedis != null && jedis.exists(key)) {
Map<String, String> map = jedis.hgetAll(key);
logger.info(">>>>" + GsonUtil.GsonString(map));
return map;
} else {
logger.info(">>>>key 不存在");
}
}
} catch (Exception e) {
logger.error("redis连接异常");
e.printStackTrace();
// 释放jedis对象
jedisPool.returnBrokenResource(jedis);
} finally {
// 返还连接池
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
return null;
}
@Override
public void hashSetMapString(String key, Map<String, String> map) {
Jedis jedis = null;
try {
if (jedisPool == null) {
poolInit();
}
if (jedisPool != null) {
jedis = jedisPool.getResource();
jedis.hmset(key, map);
}
} catch (Exception e) {
logger.error("redis连接异常");
e.printStackTrace();
// 释放jedis对象
jedisPool.returnBrokenResource(jedis);
} finally {
// 返还连接池
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
}
@Override
public void hashSetOneString(String key, String field, String value) {
Jedis jedis = null;
try {
if (jedisPool == null) {
poolInit();
}
if (jedisPool != null) {
jedis = jedisPool.getResource();
jedis.hset(key, field, value);
}
} catch (Exception e) {
logger.error("redis连接异常");
e.printStackTrace();
// 释放jedis对象
jedisPool.returnBrokenResource(jedis);
} finally {
// 返还连接池
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
}
@Override
public boolean hashExistFieldString(String key, String field) {
Jedis jedis = null;
boolean flag = false;
try {
if (jedisPool == null) {
poolInit();
}
if (jedisPool != null) {
jedis = jedisPool.getResource();
if (jedis != null && jedis.exists(key)) {
flag = jedis.hexists(key, field);
}
}
} catch (Exception e) {
logger.error("redis连接异常");
e.printStackTrace();
// 释放jedis对象
jedisPool.returnBrokenResource(jedis);
} finally {
// 返还连接池
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
return flag;
}
@Override
public void hashDelFieldString(String key, String field) {
Jedis jedis = null;
try {
if (jedisPool == null) {
poolInit();
}
if (jedisPool != null) {
jedis = jedisPool.getResource();
if (jedis != null && jedis.exists(key) && CommonUtil.isNotNullEmpty(field)) {
jedis.hdel(key, field);
}
}
} catch (Exception e) {
logger.error("redis连接异常");
e.printStackTrace();
// 释放jedis对象
jedisPool.returnBrokenResource(jedis);
} finally {
// 返还连接池
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
}
@Override
public String hashGetValueString(String key, String field) {
Jedis jedis = null;
String value = "";
try {
if (jedisPool == null) {
poolInit();
}
if (jedisPool != null) {
jedis = jedisPool.getResource();
if (jedis != null && jedis.exists(key)) {
value = jedis.hget(key, field);
}
}
} catch (Exception e) {
logger.error("redis连接异常");
e.printStackTrace();
// 释放jedis对象
jedisPool.returnBrokenResource(jedis);
} finally {
// 返还连接池
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
return value;
}
}
SerializeUtil:序列化工具类
import java.io.*;
/**
* 序列化工具类
*/
public class SerializeUtil {
/**
* 序列化
* @param value
* @return
*/
public static byte[] serialize(Object value) {
if (value == null) {
throw new NullPointerException("Can't serialize null");
}
byte[] rv = null;
ByteArrayOutputStream bos = null;
ObjectOutputStream os = null;
try {
bos = new ByteArrayOutputStream();
os = new ObjectOutputStream(bos);
os.writeObject(value);
os.close();
bos.close();
rv = bos.toByteArray();
} catch (IOException e) {
throw new IllegalArgumentException("Non-serializable object", e);
} finally {
try {
if (os != null) {
os.close();
}
if (bos != null) {
bos.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return rv;
}
/**反序列化
* @param bytes
* @return
*/
public static Object unserialize(byte[] bytes) {
Object rv = null;
ByteArrayInputStream bis = null;
ObjectInputStream is = null;
try {
if (bytes != null) {
bis = new ByteArrayInputStream(bytes);
is = new ObjectInputStream(bis);
rv = is.readObject();
is.close();
bis.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (bis != null) {
bis.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return rv;
}
}
GsonUtil
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @Title: GsonUtil.java
* @Package com.hc.utils
* @Description: gson转换工具类
* @date Creation time: 2017年9月4日
* @version V1.0
*/
public class GsonUtil {
private static Gson gson = null;
static {
if (gson == null) {
gson = new Gson();
}
}
private GsonUtil() {
}
/**
* Object to json
*
* @param object
* @return String
*/
public static String GsonString(Object object) {
String gsonString = null;
if (gson != null) {
gsonString = gson.toJson(object);
}
return gsonString;
}
/**
* json to bean
*
* @param gsonString
* @param cls
* @return T
*/
public static <T> T GsonToBean(String gsonString, Class<T> cls) throws JsonSyntaxException {
T t = null;
if (gson != null && gsonString != null && !gsonString.equals("")) {
t = gson.fromJson(gsonString, cls);
}
return t;
}
/**
* json to list
*
* @param gsonString
* @param cls
* @return List<T>
*/
public static <T> List<T> GsonToList(String gsonString, Class<T> cls) throws JsonSyntaxException {
List<T> list = new ArrayList<T>();
if (gson != null && gsonString != null && !gsonString.equals("")) {
JsonArray array = new JsonParser().parse(gsonString).getAsJsonArray();
for (final JsonElement elem : array) {
list.add(gson.fromJson(elem, cls));
}
}
return list;
}
/**
* json to list
*
* @param gsonString
* @return List<Map<String, T>>
*/
public static <T> List<Map<String, T>> GsonToListMaps(String gsonString) {
List<Map<String, T>> list = null;
if (gson != null) {
list = gson.fromJson(gsonString, new TypeToken<List<Map<String, T>>>() {
}.getType());
}
return list;
}
/**
* json to Map
*
* @param gsonString
* @return Map<String, T>
*/
public static <T> Map<String, T> GsonToMaps(String gsonString) {
Map<String, T> map = null;
if (gson != null) {
map = gson.fromJson(gsonString, new TypeToken<Map<String, T>>() {
}.getType());
}
return map;
}
/**
* Object to JsonObject
*
* @param object
* @return JsonObject
*/
public static JsonObject GetJsonObject(Object object) {
JsonObject jsonObject = null;
if (gson != null) {
jsonObject = gson.toJsonTree(object).getAsJsonObject();
}
return jsonObject;
}
/**
* @Title: GetValue
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param json
* @param key
* @return String
*/
public static String GetValue(String json, String key) throws Exception {
JsonObject jsonObject = null;
if (gson != null) {
jsonObject = new JsonParser().parse(json).getAsJsonObject();
}
if (jsonObject != null && jsonObject.has(key)) {
return jsonObject.get(key).getAsString();
}
return null;
}
/**
* @Title: parse
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param param
* @return JsonObject
*/
public static JsonObject parse(String param) throws JsonSyntaxException {
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(param);
JsonObject data = jsonElement.getAsJsonObject();
return data;
}
}
集群模式
RedisProperties
package com.ganinfo.redis;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
/**
* @className:
* @description:redis配置参数类
**/
@Data
@Component
@RefreshScope
public class RedisProperties {
/** redis集群节点 */
@Value("${spring.redis.pool.nodes}")
private String nodes;
/** 密码 */
@Value("${spring.redis.pool.password}")
private String password;
/** 连接超时时间 */
@Value("${spring.redis.pool.timeOut}")
private int timeOut;
/** 重连次数 */
@Value("${spring.redis.pool.maxAttempts}")
private int maxAttempts;
/** 可用连接实例的最大数目,默认值为8 */
@Value("${spring.redis.pool.maxActive}")
private Integer maxActive;
/**控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8*/
@Value("${spring.redis.pool.maxIdle}")
private Integer maxIdle;
/**等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。*/
@Value("${spring.redis.pool.maxWait}")
private Long maxWait;
/**#在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;*/
@Value("${spring.redis.pool.testOnBorrow}")
private Boolean testOnBorrow;
/** 有效时间 */
@Value("${spring.redis.pool.expireSeconds}")
private int expireSeconds;
/*返回值的超时时间*/
@Value("${spring.redis.pool.soTimeOut}")
private int soTimeOut;
}
JedisClusterConfig:配置
@Configuration
public class JedisClusterConfig {
@Autowired
private RedisProperties redisProperties;
@Value("${srping.redis.type:redis}")
private String redisType;
/**
* 注意:
* 这里返回的JedisCluster是单例的,并且可以直接注入到其他类中去使用
* @return
*/
@Bean
public JedisCluster getJedisCluster() {
if (!"redisCluster".equals(redisType)){
return null;
}
String[] serverArray = redisProperties.getNodes().split(",");//获取服务器数组(这里要相信自己的输入,所以没有考虑空指针问题)
Set<HostAndPort> nodes = new HashSet<>();
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(redisProperties.getMaxIdle());
config.setMaxTotal(redisProperties.getMaxActive());
config.setTestOnBorrow(redisProperties.getTestOnBorrow());
config.setMaxIdle(redisProperties.getMaxIdle());
for (String ipPort : serverArray) {
String[] ipPortPair = ipPort.split(":");
nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim())));
}
return new JedisCluster(nodes,redisProperties.getTimeout(),5000,redisProperties.getMaxAttempts(),redisProperties.getPassword(),config);
}
}
JedisClusterTemplate
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisCluster;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* @className:
* @description:redis集群工具类
* @date 2018-02-24 13:27
**/
@Component
public class JedisClusterTemplate implements RedisService {
private Logger logger = Logger.getLogger(JedisClusterTemplate.class);
private static final String SET_IF_NOT_EXIST = "NX";
private static final String SET_WITH_EXPIRE_TIME = "PX";
@Autowired
private JedisCluster jedisCluster;
@Autowired
private RedisProperties redisProperties;
private static final String KEY_SPLIT = "lc_vc_"; //用于隔开缓存前缀与缓存键值
private byte[] buildKey(String key) {
String str = KEY_SPLIT + key;
return str.getBytes();
}
/**
* 设置缓存
*
* @param key 缓存key
* @param value 缓存value
*/
@Override
public void set(String key, String value) {
jedisCluster.set(buildKey(key), SerializeUtil.serialize(value));
}
/**
* 设置缓存,并且自己指定过期时间
*
* @param key
* @param value
* @param expireTime 过期时间
*/
@Override
public void setWithExpireTime(String key, String value, int expireTime) {
jedisCluster.setex(buildKey(key), expireTime, SerializeUtil.serialize(value));
}
/**
* 设置缓存,并且由配置文件指定过期时间
*
* @param key
* @param value
*/
@Override
public void setWithExpireTime(String key, String value) {
int EXPIRE_SECONDS = redisProperties.getExpireSeconds();
jedisCluster.setex(buildKey(key), EXPIRE_SECONDS, SerializeUtil.serialize(value));
}
/**
* 获取指定key的缓存
*
* @param key
*/
@Override
public String get(String key) {
if (exists(key)) {
byte[] bytes = jedisCluster.get(buildKey(key));
Object unserialize = SerializeUtil.unserialize(bytes);
return unserialize.toString();
} else {
return null;
}
}
/**
* 删除指定key的缓存
*
* @param key
*/
@Override
public void del(String key) {
jedisCluster.del(buildKey(key));
}
@Override
public void delString(String key) {
jedisCluster.del(key);
}
/**
* 判断key是否存在
*
* @param key
*/
@Override
public Boolean exists(String key) {
Boolean exists = jedisCluster.exists(buildKey(key));
return exists;
}
/**
* 缓存Bean类型
*
* @param key
* @param bean
*/
@Override
public <T> void setBean(String key, Object bean) {
jedisCluster.set(buildKey(key), SerializeUtil.serialize(bean));
}
/**
* 获取Bean类型
*
* @param key
*/
@Override
public <T> T getBean(String key) {
if (exists(key)) {
byte[] bytes = jedisCluster.get(buildKey(key));
T bean = (T) SerializeUtil.unserialize(bytes);
return bean;
} else {
return null;
}
}
/**
* 缓存List类型
*
* @param key
* @param list
*/
@Override
public <T> void setList(String key, List<T> list) {
jedisCluster.set(buildKey(key), SerializeUtil.serialize(list));
}
/**
* 获取List类型
*
* @param key
*/
@Override
public <T> List<T> getList(String key) {
if (exists(key)) {
byte[] bytes = jedisCluster.get(buildKey(key));
List<T> list = (List<T>) SerializeUtil.unserialize(bytes);
return list;
} else {
return null;
}
}
/**
* 用户登录
*
* @param userCode
*/
@Override
public String login(String userCode) {
String accessToken = UUIDUtil.creatUUID();
int EXPIRE_SECONDS = redisProperties.getExpireSeconds();
if (jedisCluster.exists(userCode)) {
//销毁
String s = jedisCluster.get(userCode);
if (CommonUtil.isNotNullEmpty(s)) {
jedisCluster.del(s);
}
jedisCluster.del(userCode);
}
//缓存新token
String setex = jedisCluster.setex(userCode, EXPIRE_SECONDS, accessToken);
String setex1 = jedisCluster.setex(accessToken, EXPIRE_SECONDS, userCode);
logger.info("setex" + setex);
logger.info("setex1" + setex1);
return accessToken;
}
/**
* 用户校验
*
* @param accessToken
*/
@Override
public void validate(String accessToken) {
int EXPIRE_SECONDS = redisProperties.getExpireSeconds();
if (jedisCluster.exists(accessToken)) {
String s = jedisCluster.get(accessToken);
jedisCluster.expire(s, EXPIRE_SECONDS);
jedisCluster.expire(accessToken, EXPIRE_SECONDS);
}
}
/**
* 用户退出
*
* @param accessToken
*/
@Override
public void logout(String accessToken) {
// int EXPIRE_SECONDS = redisProperties.getExpireSeconds();
if (jedisCluster.exists(accessToken)) {
String s = jedisCluster.get(accessToken);
jedisCluster.del(s);
jedisCluster.del(accessToken);
}
}
/**
* 获取用户id
*
* @param accessToken
*/
@Override
public String getUserId(String accessToken) {
if (jedisCluster.exists(accessToken)) {
String s = jedisCluster.get(accessToken);
return s;
} else {
return null;
}
}
@Override
public String getSupportType() {
return "redisCluster";
}
@Override
public long getValue(String key) {
if (jedisCluster.exists(key)) {
String s = jedisCluster.get(key);
return Long.valueOf(s);
} else {
return 0;
}
}
@Override
public String setLock(String lockKey, String requestId, int expireTime) {
String result = jedisCluster.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
return result;
}
@Override
public Object 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";
Object result = jedisCluster.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
return result;
}
@Override
public String getString(String key) {
if (jedisCluster.exists(key)) {
String s = jedisCluster.get(key);
return s;
} else {
return null;
}
}
@Override
public void dels(String pattern) {
}
public void setObject(String key, String value) {
jedisCluster.set(key, value);
}
/**
* @param key
* @author:shuyu.wang
* @description:根据key查询hash
* @date: 2018/12/5 18:26
* @param: null
* @return: null
*/
@Override
public Map<String, String> getHash(String key) {
if (jedisCluster.exists(key)) {
Map<String, String> map = jedisCluster.hgetAll(key);
return map;
}
return null;
}
@Override
public void hashSetMapString(String key, Map<String, String> map) {
jedisCluster.hmset(key,map);
}
@Override
public void hashSetOneString(String key, String field, String value) {
jedisCluster.hset(key,field,value);
}
@Override
public boolean hashExistFieldString(String key, String field) {
boolean flag=true;
flag=jedisCluster.hexists(key,field);
return flag;
}
@Override
public void hashDelFieldString(String key, String field) {
if(hashExistFieldString(key,field)){
long num=jedisCluster.hdel(key,field);
if(!CommonUtil.isNotLongNull(num)){
logger.error("========删除key:"+key+"; field:"+field+" 失败==========");
}
}else {
logger.info("========key不存在==========");
}
}
@Override
public String hashGetValueString(String key, String field) {
String hValue="";
if(hashExistFieldString(key,field)){
hValue=jedisCluster.hget(key,field);
}
return hValue;
}
}
最后
以上就是耍酷煎饼为你收集整理的springboo集成redis随笔的全部内容,希望文章能够帮你解决springboo集成redis随笔所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复