当前位置:   article > 正文

基于SpringBoot和Redis实现短信验证码功能_springboot redis发送短信校验

springboot redis发送短信校验

基于SpringBoot和Redis实现短信验证码功能

app中使用短信登录,使用redis实现

(一)准备工作

1.1引入相关依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <exclusions>
        <exclusion>
            <artifactId>spring-data-redis</artifactId>
            <groupId>org.springframework.data</groupId>
        </exclusion>
        <exclusion>
            <artifactId>lettuce-core</artifactId>
            <groupId>io.lettuce</groupId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>2.6.2</version>
</dependency>
<dependency>
    <groupId>io.lettuce</groupId>
    <artifactId>lettuce-core</artifactId>
    <version>6.1.6.RELEASE</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

1.2在application.yaml文件中配置相关数据

redis:
  host: 192.168.***.***
  port: 6379
  password: 123456
  lettuce:
    pool:
      max-active: 10
      max-idle: 10
      min-idle: 1
      time-between-eviction-runs: 10s
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

(二)短信的发送

2.1思路

用户从前端发送手机号到后台服务器,首先需要经过service层验证手机号格式是否正确,将手机号传给某个接口(市面上很多),验证通过,发送验证码。然后service层随机生成一个6位数的随机字符串。之后首先将生成的验证码保存在redis中并设置有效时间(防止redis内存占满的情况),(这里采用String数据结构保存验证码,并且以手机号作为key)。然后向用户提供的手机号上发送本次随机生成的验证码。

2.2代码编写

@Override
public Result sendCode(String phone, HttpSession session) {
    //1校验手机号
    if(RegexUtils.isPhoneInvalid(phone)){
        //2如果不符合,返回错误信息
        return Result.fail("手机号格式错误");
    }
    //3符合生成验证码
    String code = RandomUtil.randomNumbers(6);
    //4保存验证码到redis,并设置有效期(防止内存占满setex)
    stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);
    //5发送验证码(本业务的功能在于学习redis,发送验证码需要整合第三方接口,这里假装发送一下)
    log.debug("发送验证码成功,验证码为{}",code);
    //返回声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签