现在的场景是需要做 token 验证,那么用户退出登录之后,我们给他设置一个新的 token,然后当用户拿着已经注销了的token再进行访问验证时,到 Redis 里查看对比两个token是否一致,如果不一致说明token已过期
所以现在我们需要在 验证 token 的 Class 里面使用 RedisService 从数据库里拿出 token 做对比
由于工具类是 静态的方法,并且也不是 controller,不能直接使用注解注入
所以 RedisService 的注入方式如下:
public static RedisService redisService ;
@Autowired
public void setRedisService(RedisService redisService){
JwtUtil.redisService = redisService;
}
首先安装 Redis: Redis 安装教程
然后在 SpringBoot 里配置Redis
添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
application.properties 里
#################redis基础配置#################
spring.redis.database=0
spring.redis.host=localhost
spring.redis.password= #默认为空
spring.redis.port=6379
# 连接超时时间 单位 ms(毫秒)
spring.redis.timeout=0
#################redis线程池设置#################
# 连接池中的最大空闲连接,默认值也是8。
spring.redis.jedis.pool.max-idle=500
#连接池中的最小空闲连接,默认值也是0。
spring.redis.jedis.pool.min-idle=50
# 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
spring.redis.jedis.pool.max-active=8
# 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException
# spring.redis.jedis.pool.max-wait=1000ms
#################redis哨兵设置#################
# Redis服务器master的名字
#spring.redis.sentinel.master=master8026
# redis-sentinel的配置地址和端口
#spring.redis.sentinel.nodes=10.189.80.25:26379,10.189.80.26:26379,10.189.80.27:26378
创建一个 RedisConfig类 配置 Redis连接
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springf