工具类:
package com.ljxx.service.common; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.*; import org.springframework.data.redis.serializer.StringRedisSerializer; import org.springframework.data.redis.support.atomic.RedisAtomicLong; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.io.Serializable; import java.util.Date; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; @Service public class RedisService { @Autowired private RedisTemplate redisTemplate; @Autowired private StringRedisTemplate stringRedisTemplate; @Value("${system.redisPre}") private String redisPre; /** * string类型 */ //删除key public void deleteKey(String key) { stringRedisTemplate.delete(redisPre + key); } //判断key存在 public boolean keyIsExists(String key) { return stringRedisTemplate.hasKey(redisPre + key); } //设置key失效时间,以秒为单位 public void setKeyTimeOut(String key, long second) { stringRedisTemplate.expire(redisPre + key, second, TimeUnit.SECONDS); } //设置值 public void setValue(String key, String val) { stringRedisTemplate.boundValueOps(redisPre + key).set(val); } //获取值 public String getValue(String key) { return stringRedisTemplate.boundValueOps(redisPre + key).get(); } /** * object类型 */ //存入对象 public void setObject(String key, Object obj) { getRedisTemplate().boundValueOps(redisPre + key).set(obj); } //获取对象 public Object getObject(String key) { return getRedisTemplate().boundValueOps(redisPre + key).get(); } //删除对象 public void delObject(String key) { getRedisTemplate().delete(redisPre + key); } //设置对象过期时间 public void setObjectTimeOut(String key, long second) { getRedisTemplate().expire(redisPre + key, second, TimeUnit.SECONDS); } //判断对象是否存在 public boolean objectIsExists(String key) { return getRedisTemplate().hasKey(redisPre + key); } //获取RedisTemplate,把key进行string序列化,那么在库中就显示的原始的key值,否则就是16进制的值不方便。 private RedisTemplate getRedisTemplate() { //设置key是string类型的序列 redisTemplate.setKeySerializer(new StringRedisSerializer()); //设置hashKey是string类型的序列 redisTemplate.setHashKeySerializer(new StringRedisSerializer()); return redisTemplate; } }
使用工具类:注入
@Autowired private RedisService redisUtil;
调用工具类的方法:
if (!redisUtil.objectIsExists(token)) { return Result.error("token已经失效!"); }
User user = (User) redisUtil.getObject(token);