利用Redis优化登录模块
为了减少数据库压力,提高系统速度,在项目中引入了Redis。
之前登陆验证码信息存储在Session中。每次请求前,拦截器会验证登录信息,每次到从数据库中去用户信息。通过Redis改进这两项功能。
首先安装redis,并导入redis依赖,配置好redis。
对于验证码信息,每次获取验证码请求都要有一个主键来在redis中存验证码的值,对于同一个客户端我们又希望是相同的key,因此我们采用在cookie中保存UUID的方式,代码如下:
@RequestMapping(path = "/kaptcha", method = RequestMethod.GET) public void getKaptcha(HttpServletResponse response/*, HttpSession session*/) { // 生成验证码 String text = kaptchaProducer.createText(); BufferedImage image = kaptchaProducer.createImage(text); // 将验证码存入session // session.setAttribute("kaptcha", text); // 验证码的归属 String kaptchaOwner = CommunityUtil.generateUUID(); Cookie cookie = new Cookie("kaptchaOwner", kaptchaOwner); cookie.setMaxAge(60); cookie.setPath(contextPath); response.addCookie(cookie); // 将验证码存入Redis String redisKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner); redisTemplate.opsForValue().set(redisKey, text, 60, TimeUnit.SECONDS); // 将突图片输出给浏览器 response.setContentType("image/png"); try { OutputStream os = response.getOutputStream(); ImageIO.write(image, "png", os); } catch (IOException e) { logger.error("响应验证码失败:" + e.getMessage()); } }
查询用户信息时,我们只需重写service中的通过用户id查询用户的方法,若redis中取不到,则从数据库中取,并且将user对象转为json存入到redis中。此处要注意一点,为了保持缓存与数据库的一致性,在对用户进行改动时,要增加删除缓存操作。代码如下
public User findUserById(int id) { // return userMapper.selectById(id); User user = getCache(id); if (user == null) { user = initCache(id); } return user; } private User initCache(int userId) { User user = userMapper.selectById(userId); String redisKey = RedisKeyUtil.getUserKey(userId); redisTemplate.opsForValue().set(redisKey, user, 3600, TimeUnit.SECONDS); return user; }

浙公网安备 33010602011771号