本文主要讲解mall整合Redis的过程,以短信验证码的存储验证为例。

Redis的安装和启动

Redis是用C语言开发的一个高性能键值对数据库,可用于数据缓存,主要用于处理大量数据的高访问负载。

mall整合Redis实现缓存功能 - 图1

  • 下载完后解压到指定目录

mall整合Redis实现缓存功能 - 图2

  • 在当前地址栏输入cmd后,执行redis的启动命令:redis-server.exe redis.windows.conf

mall整合Redis实现缓存功能 - 图3

整合Redis

添加项目依赖

在pom.xml中新增Redis相关依赖

  1. <!--redis依赖配置-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-redis</artifactId>
  5. </dependency>

修改SpringBoot配置文件

在application.yml中添加Redis的配置及Redis中自定义key的配置。

在spring节点下添加Redis的配置

  1. redis:
  2. host: localhost # Redis服务器地址
  3. database: 0 # Redis数据库索引(默认为0)
  4. port: 6379 # Redis服务器连接端口
  5. password: # Redis服务器连接密码(默认为空)
  6. jedis:
  7. pool:
  8. max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
  9. max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制)
  10. max-idle: 8 # 连接池中的最大空闲连接
  11. min-idle: 0 # 连接池中的最小空闲连接
  12. timeout: 3000ms # 连接超时时间(毫秒)

在根节点下添加Redis自定义key的配置

  1. # 自定义redis key
  2. redis:
  3. key:
  4. prefix:
  5. authCode: "portal:authCode:"
  6. expire:
  7. authCode: 120 # 验证码超期时间

添加RedisService接口用于定义一些常用Redis操作

  1. package com.macro.mall.tiny.service;
  2. /**
  3. * redis操作Service,
  4. * 对象和数组都以json形式进行存储
  5. * Created by macro on 2018/8/7.
  6. */
  7. public interface RedisService {
  8. /**
  9. * 存储数据
  10. */
  11. void set(String key, String value);
  12. /**
  13. * 获取数据
  14. */
  15. String get(String key);
  16. /**
  17. * 设置超期时间
  18. */
  19. boolean expire(String key, long expire);
  20. /**
  21. * 删除数据
  22. */
  23. void remove(String key);
  24. /**
  25. * 自增操作
  26. * @param delta 自增步长
  27. */
  28. Long increment(String key, long delta);
  29. }

注入StringRedisTemplate,实现RedisService接口

  1. package com.macro.mall.tiny.service.impl;
  2. import com.macro.mall.tiny.service.RedisService;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.data.redis.core.StringRedisTemplate;
  5. import org.springframework.stereotype.Service;
  6. import java.util.concurrent.TimeUnit;
  7. /**
  8. * redis操作Service的实现类
  9. * Created by macro on 2018/8/7.
  10. */
  11. @Service
  12. public class RedisServiceImpl implements RedisService {
  13. @Autowired
  14. private StringRedisTemplate stringRedisTemplate;
  15. @Override
  16. public void set(String key, String value) {
  17. stringRedisTemplate.opsForValue().set(key, value);
  18. }
  19. @Override
  20. public String get(String key) {
  21. return stringRedisTemplate.opsForValue().get(key);
  22. }
  23. @Override
  24. public boolean expire(String key, long expire) {
  25. return stringRedisTemplate.expire(key, expire, TimeUnit.SECONDS);
  26. }
  27. @Override
  28. public void remove(String key) {
  29. stringRedisTemplate.delete(key);
  30. }
  31. @Override
  32. public Long increment(String key, long delta) {
  33. return stringRedisTemplate.opsForValue().increment(key,delta);
  34. }
  35. }

添加UmsMemberController

添加根据电话号码获取验证码的接口和校验验证码的接口

  1. package com.macro.mall.tiny.controller;
  2. import com.macro.mall.tiny.common.api.CommonResult;
  3. import com.macro.mall.tiny.service.UmsMemberService;
  4. import io.swagger.annotations.Api;
  5. import io.swagger.annotations.ApiOperation;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.stereotype.Controller;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RequestMethod;
  10. import org.springframework.web.bind.annotation.RequestParam;
  11. import org.springframework.web.bind.annotation.ResponseBody;
  12. /**
  13. * 会员登录注册管理Controller
  14. * Created by macro on 2018/8/3.
  15. */
  16. @Controller
  17. @Api(tags = "UmsMemberController", description = "会员登录注册管理")
  18. @RequestMapping("/sso")
  19. public class UmsMemberController {
  20. @Autowired
  21. private UmsMemberService memberService;
  22. @ApiOperation("获取验证码")
  23. @RequestMapping(value = "/getAuthCode", method = RequestMethod.GET)
  24. @ResponseBody
  25. public CommonResult getAuthCode(@RequestParam String telephone) {
  26. return memberService.generateAuthCode(telephone);
  27. }
  28. @ApiOperation("判断验证码是否正确")
  29. @RequestMapping(value = "/verifyAuthCode", method = RequestMethod.POST)
  30. @ResponseBody
  31. public CommonResult updatePassword(@RequestParam String telephone,
  32. @RequestParam String authCode) {
  33. return memberService.verifyAuthCode(telephone,authCode);
  34. }
  35. }

添加UmsMemberService接口

  1. package com.macro.mall.tiny.service;
  2. import com.macro.mall.tiny.common.api.CommonResult;
  3. /**
  4. * 会员管理Service
  5. * Created by macro on 2018/8/3.
  6. */
  7. public interface UmsMemberService {
  8. /**
  9. * 生成验证码
  10. */
  11. CommonResult generateAuthCode(String telephone);
  12. /**
  13. * 判断验证码和手机号码是否匹配
  14. */
  15. CommonResult verifyAuthCode(String telephone, String authCode);
  16. }

添加UmsMemberService接口的实现类UmsMemberServiceImpl

生成验证码时,将自定义的Redis键值加上手机号生成一个Redis的key,以验证码为value存入到Redis中,并设置过期时间为自己配置的时间(这里为120s)。校验验证码时根据手机号码来获取Redis里面存储的验证码,并与传入的验证码进行比对。

  1. package com.macro.mall.tiny.service.impl;
  2. import com.macro.mall.tiny.common.api.CommonResult;
  3. import com.macro.mall.tiny.service.RedisService;
  4. import com.macro.mall.tiny.service.UmsMemberService;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.beans.factory.annotation.Value;
  7. import org.springframework.stereotype.Service;
  8. import org.springframework.util.StringUtils;
  9. import java.util.Random;
  10. /**
  11. * 会员管理Service实现类
  12. * Created by macro on 2018/8/3.
  13. */
  14. @Service
  15. public class UmsMemberServiceImpl implements UmsMemberService {
  16. @Autowired
  17. private RedisService redisService;
  18. @Value("${redis.key.prefix.authCode}")
  19. private String REDIS_KEY_PREFIX_AUTH_CODE;
  20. @Value("${redis.key.expire.authCode}")
  21. private Long AUTH_CODE_EXPIRE_SECONDS;
  22. @Override
  23. public CommonResult generateAuthCode(String telephone) {
  24. StringBuilder sb = new StringBuilder();
  25. Random random = new Random();
  26. for (int i = 0; i < 6; i++) {
  27. sb.append(random.nextInt(10));
  28. }
  29. //验证码绑定手机号并存储到redis
  30. redisService.set(REDIS_KEY_PREFIX_AUTH_CODE + telephone, sb.toString());
  31. redisService.expire(REDIS_KEY_PREFIX_AUTH_CODE + telephone, AUTH_CODE_EXPIRE_SECONDS);
  32. return CommonResult.success(sb.toString(), "获取验证码成功");
  33. }
  34. //对输入的验证码进行校验
  35. @Override
  36. public CommonResult verifyAuthCode(String telephone, String authCode) {
  37. if (StringUtils.isEmpty(authCode)) {
  38. return CommonResult.failed("请输入验证码");
  39. }
  40. String realAuthCode = redisService.get(REDIS_KEY_PREFIX_AUTH_CODE + telephone);
  41. boolean result = authCode.equals(realAuthCode);
  42. if (result) {
  43. return CommonResult.success(null, "验证码校验成功");
  44. } else {
  45. return CommonResult.failed("验证码不正确");
  46. }
  47. }
  48. }

运行项目

访问Swagger的API文档地址http://localhost:8080/swagger-ui.html ,对接口进行测试。

mall整合Redis实现缓存功能 - 图4

项目源码地址

https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-03