先放上参考链接
springboot+redis实现token机制_风情-CSDN博客_springboot+redis+token
请先配置好redis
放上正确代码
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.6.2</version>
</dependency>
这里如果报错 可能是依赖版本问题
<version>2.6.2</version>
*************************** APPLICATION FAILED TO START *************************** Description: A component required a bean of type 'org.springframework.data.redis.core.RedisTemplate' that could not be found. The following candidates were found but could not be injected: - Bean method 'redisTemplate' in 'RedisAutoConfiguration' not loaded because @ConditionalOnMissingBean (names: redisTemplate; SearchStrategy: all) found beans named redisTemplate Action: Consider revisiting the entries above or defining a bean of type 'org.springframework.data.redis.core.RedisTemplate' in your configuration.
controller.class
@Resource
private RedisTemplate<String,Object>redisTemplate;
@RequestMapping("LoginToken")
@ResponseBody
public String CheckLogin(@RequestParam("user_name") String acctName,
@RequestParam("user_password") String accPass){
System.out.println("用户名:" + acctName);
System.out.println("密码:" + accPass);
Map<String, Object> map_res = new HashMap<>();
//用户检索
List<UserBean> userlist = loginService.findUser(acctName, accPass);
System.out.println(JSON.toJSONString(userlist));
if (userlist.size() > 0){//登录成功
//生成token令牌
String token = String.valueOf(UUID.randomUUID());
System.out.println(token);
//存到redis数据库 token 用户名 有效时间
redisTemplate.opsForValue().set(token, JSON.toJSONString(userlist), Duration.ofHours(1));
//redisTemplate.opsForValue().set(token,acctName, Duration.ofHours(1));
System.out.println("登录成功");
map_res.put("msg", "成功");
map_res.put("code", "200");
map_res.put("user_name", acctName);
map_res.put("token", token);
} else {
map_res.put("msg", "失败");
map_res.put("code", "500");
}
return JSON.toJSONString(map_res);
}
application.properties
##指定使用redis数据库索引(默认为0)
spring.redis.database=0
##指定Redis服务器地址
spring.redis.host=127.0.0.1
##指定Redis端口号
spring.redis.port=6379
##指定Redis密码 (没有可以不写)
#spring.redis.password=123456
总结
- 首先是pom文件需要新增依赖
- token生成可以使用
UUID这个库只需要一行代码 非常好用 具体原理可以看 Java UUID的底层原理 - March On - 博客园 (cnblogs.com) - token的上传 实际上也只需要一行代码
首先声明
@Resource private RedisTemplate<String,Object>redisTemplate;上传代码是redisTemplate.opsForValue().set(token,userlist, Duration.ofHours(1));唯一标识(主键 token就行),要存储的数据,数据生效时间(过期后会自动删除 好评)