水生的网络日志 水生的网络日志
首页
  • 前言
  • Java核心
  • 企业级开发
  • 数据库
  • 计算机基础
  • 求职面试
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 分类
  • 标签
  • 归档
关于
GitHub (opens new window)

水生

记录我的所思、所学、所想
首页
  • 前言
  • Java核心
  • 企业级开发
  • 数据库
  • 计算机基础
  • 求职面试
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 分类
  • 标签
  • 归档
关于
GitHub (opens new window)
  • 前言

  • Java核心

  • 企业级开发

    • Spring Boot开发

      • 创建Maven父子项目
      • Spring Boot整合MyBatis
      • Spring Boot整合Swagger
      • Spring Boot整合Redis实现缓存验证码
        • Redis的安装和启动
        • 整合Redis
          • 添加项目依赖
          • 修改SpringBoot配置文件
          • 在spring节点下添加Redis的配置
          • 在根节点下添加Redis自定义key的配置
          • 添加RedisService接口用于定义一些常用Redis操作
          • 注入StringRedisTemplate,实现RedisService接口
        • 实现会员登录注册接口
          • 添加UmsMemberController
          • 添加UmsMemberService接口
          • 添加UmsMemberService接口的实现类UmsMemberServiceImpl
          • 运行项目
        • 思维导图
      • Spring Boot整合Spring Sercurity和JWT
      • Spring Boot整合Spring Task实现定时任务
      • Spring Boot整合ElasticSearch实现商品搜索
      • Spring Boot整合MongoDB实现文档操作
      • Spring Boot整合RabbitMQ实现延迟消息
    • Spring Cloud开发

  • 数据库

  • 计算机基础

  • 求职面试

  • 知识库
  • 企业级开发
  • Spring Boot开发
水生
2019-12-24
目录

Spring Boot整合Redis实现缓存验证码

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

# Redis的安装和启动

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

  • 通过docker安装Reids,安装教程参考[Docker 安装 Redis by 菜鸟教程](Docker 安装 Redis)
docker pull redis:latest
1
  • 启动Redis容器
docker run -itd --name redis-test -p 6379:6379 redis
1
  • 连接测试

image-20211224203045726


# 整合Redis

# 添加项目依赖

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

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

# 修改SpringBoot配置文件

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

# 在spring节点下添加Redis的配置

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

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

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

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

package com.sds.sercurity.service;

/**
 * @description: Redis操作Service
 * @author: shuds
 * @date: 2021/12/24
 **/
public interface RedisService {
    /**
     * 存储数据
     * @param key
     * @param value
     */
    void set(String key, String value);

    /**
     * 获取数据
     * @param key
     */
    String get(String key);

    /**
     * 设置超时时间
     * @param key
     * @param expire
     * @return
     */
    boolean expire(String key, long expire);

    /**
     * 删除数据
     * @param key
     */
    void remove(String key);

    /**
     * 自增长操作
     * @param key
     * @param delta 自增长步长
     */
    Long increment(String key, long delta);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

# 注入StringRedisTemplate,实现RedisService接口

package com.sds.sercurity.service.Impl;

import com.sds.sercurity.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @description: Redis操作实现类
 * @author: shuds
 * @date: 2021/12/24
 **/
@Service
public class RedisServiceImpl implements RedisService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void set(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    @Override
    public String get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    @Override
    public boolean expire(String key, long expire) {
        return redisTemplate.expire(key, expire, TimeUnit.SECONDS);
    }

    @Override
    public void remove(String key) {
        redisTemplate.delete(key);
    }

    @Override
    public Long increment(String key, long delta) {
        return redisTemplate.opsForValue().increment(key, delta);
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

# 实现会员登录注册接口

# 添加UmsMemberController

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

package com.sds.sercurity.controller;

import com.sds.sercurity.common.api.CommonResult;
import com.sds.sercurity.service.UmsMemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @description: 会员登录注册Controller
 * @author: shuds
 * @date: 2021/12/24
 **/
@RestController
@RequestMapping("/sso")
@Api(tags = "UmsMemberController", description = "会员登录注册管理")
public class UmsMemberController {
    @Autowired
    private UmsMemberService umsMemberService;

    @ApiOperation("获取验证码")
    @GetMapping("/getAuthCode")
    public CommonResult getAuthCode(@RequestParam String telephone) {
        return umsMemberService.generateAuthCode(telephone);
    }

    @ApiOperation("判断验证码是否正确")
    @PostMapping("/verifyAuthCode")
    public CommonResult updatePassword(@RequestParam String telephone, @RequestParam String authCode) {
        return umsMemberService.verifyAuthCode(telephone, authCode);
    }

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

# 添加UmsMemberService接口

package com.sds.sercurity.service;

import com.sds.sercurity.common.api.CommonResult;

/**
 * @description: TODO
 * @author: shuds
 * @date: 2021/12/24
 **/
public interface UmsMemberService {
    /**
     * 生成验证码
     * @param telephone
     * @return
     */
    CommonResult generateAuthCode(String telephone);

    /**
     * 判断验证码是否正确
     * @param telephone
     * @param authCode
     * @return
     */
    CommonResult verifyAuthCode(String telephone, String authCode);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

# 添加UmsMemberService接口的实现类UmsMemberServiceImpl

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

package com.sds.sercurity.service.Impl;

import com.sds.sercurity.common.api.CommonResult;
import com.sds.sercurity.service.RedisService;
import com.sds.sercurity.service.UmsMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.RedisServer;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;

/**
 * @description: 会员登录注册服务实现类
 * @author: shuds
 * @date: 2021/12/24
 **/
@Service
public class UmsMemberServiceImpl implements UmsMemberService {
    @Autowired
    private RedisService redisService;
    @Value("${redis.key.prefix.authCode}")
    private String REDIX_KEY_PREFIX_AUTH_CODE;
    @Value("${redis.key.expire.authCode}")
    private Long AUTH_CODE_EXPIRE_SECONDS;

    @Override
    public CommonResult generateAuthCode(String telephone) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }

        redisService.set(REDIX_KEY_PREFIX_AUTH_CODE + telephone, sb.toString());
        redisService.expire(REDIX_KEY_PREFIX_AUTH_CODE + telephone, AUTH_CODE_EXPIRE_SECONDS);
        return CommonResult.success(sb.toString(), "活鱼验证码成功");
    }

    @Override
    public CommonResult verifyAuthCode(String telephone, String authCode) {
        if (StringUtils.isEmpty(authCode)) {
            return CommonResult.failed("请输入验证码");
        }
        String realAuthCode = redisService.get(REDIX_KEY_PREFIX_AUTH_CODE + telephone);
        if (realAuthCode.equals(authCode)) {
            return CommonResult.success("验证码校验成功");
        }else
            return CommonResult.failed("验证码不正确");
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

# 运行项目

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

image-20211224205503298

docker run -p 6379:6379 --name redis \
-v /mydata/redis/data:/data \
-v /mydata/redis/redis.conf:/etc/redis/redis.conf \
-d redis:latest redis-server --appendonly yes --requirepass "123456"

1
2
3
4
5

# 思维导图

image-20211224210218466

编辑 (opens new window)
#Spring Boot#Redis
上次更新: 2022/11/26, 22:18:38
Spring Boot整合Swagger
Spring Boot整合Spring Sercurity和JWT

← Spring Boot整合Swagger Spring Boot整合Spring Sercurity和JWT→

最近更新
01
基于微服务案例的Maven实战
05-08
02
使用Seata彻底解决Spring Cloud中的分布式事务问题
11-26
03
Spring Boot整合RabbitMQ实现延迟消息
11-26
更多文章>
Theme by Vdoing | Copyright © 2019-2022 水生 | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式