SpringBoot + Redis 以及在工具类里注入 Service(Redis)

本文介绍如何在SpringBoot应用中结合Redis进行token验证。当用户登出后,系统生成新token并利用Redis服务比较旧token的有效性。由于验证类非Controller,无法直接注解注入,通过配置Redis、创建接口及实现类,实现在静态方法中注入RedisService,以完成token的数据库比对。最后,通过测试确保Redis连接成功。
摘要由CSDN通过智能技术生成

现在的场景是需要做 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
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值