redis缓存
springboot+redis
@Cacheable(name="",key="")
:表示将该对象以name+key
为键存入redis
数据库。@CacheEvict(name="",key="")
:表示将以name+key
为键的记录删除,以更新缓存,使得缓存数据与数据库数据一致。@CacheConfig(name="")
:注解在类上,表示统一指定缓存的name
字段。
redis存储与登录拦截
- 在
pom.xml
文件中引入spring-boot-starter-data-redis
文件 - 在
application.properties
中配置redis
相关信息,包括端口号(默认6379)、主机ip和密码。 - 通过
StringRedisTemplate
类(RedisTemplate
的子类,此处是操作字符串类型的redis
)对redis
数据库进行操作。 - 用户登录后将其唯一
id
与自动生成的key
存入redis
数据库(key-value
形式)。注意设置过期时间(很重要)。 - 同时将
key
设置到cookie
中,通过cookie
中key
是否能对应到redis
数据库中的值判断用户是否已登录。 - 退出登录,则通过
HttpResponse
中存在的cookie
(redis
的key
),删除对应位于redis
中的数据记录;并同时将该cookie
的过期时间(maxAge
)设置为0;即删除此cookie
。
@Autowired
private StringRedisTemplate stringRedisTemplate;//redis操作类
@PostMapping("/login")
public String login(@RequestParam String openid,
HttpServletResponse response,
Model model){
//根据openid查询mysql数据库中是否存在该用户
Seller seller=sellerService.findOneByOpenid(openid);
if(null==seller){
return "login";//登录失败
}
//若存在,将用户Openid存入redis数据库,并设置过期时间
String token_key= UUID.randomUUID().toString();
Integer expire= RedisConstant.EXPIRE;//过期时间使用枚举
//存入redis数据库
stringRedisTemplate.opsForValue().set(RedisConstant.KEY_PREFIX+token_key,openid,expire, TimeUnit.SECONDS);
//将redis数据库中对应的用户openid和key信息设置为token
Cookie cookie=new Cookie(CookieConstant.TOKEN_KEY,RedisConstant.KEY_PREFIX+token_key);
cookie.setMaxAge(RedisConstant.EXPIRE);
cookie.setPath("/");
response.addCookie(cookie);
return "redirect:/sellOrder/view";
}