3.登录发送验证码

登录发送验证码

1.接口说明

1665631729848

2.流程分析

客户端发送请求

服务端调用第三方组件发送验证码

验证码发送成功,存入redis

响应客户端,客户端跳转到输入验证码页面

1665631686151

3.代码实现

1665632031716

3.1在tanhua-app-server模块的application.yml配置文件中添加配置

server:
  port: 8080 #服务端口
spring:
  application:
    name: tanhua-app-server #服务名称
  redis: #redis配置
    port: 6379
    host: 192.168.136.160
  cloud: #nacos配置
    nacos:
      discovery:
        server-addr: 192.168.136.160:8848
dubbo:
  registry:
    address: spring-cloud://localhost
  consumer:
    check: false
  cloud:
    subscribed-services: 'tanhua-app-server'
tanhua:
  sms:
    signName: 物流云商
    templateCode: SMS_106590012
    accessKey: LTAI4GKgob9vZ53k2SZdyAC7
    secret: LHLBvXmILRoyw0niRSBuXBZewQ30la

3.2为tanhua-app-server模块新建启动类AppServerApplication

package com.tanhua.server;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AppServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(AppServerApplication.class, args);
    }
}

3.3创建controller包创建LoginController接收请求

package com.tanhua.server.controller;

import com.tanhua.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/user")
public class LOginController {

    @Autowired
    private UserService userService;


    @PostMapping("/login")
    public void login(@RequestBody Map map){
        //1.接收参数
        String  phone = (String) map.get("phone");

        //2.调用service
        String randomCode = userService.sendMsm(phone);
    }
}

3.4UserService

package com.tanhua.server.service;

import com.tanhua.autoconfig.template.SmsTemplate;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Service
public class UserService {

    @Autowired
    private SmsTemplate smsTemplate;  //发送手机验证码模板

    @Autowired
    private RedisTemplate<String ,String> redisTemplate;

    public void sendMsm(String phone) {

        //1.生成六位数的随机号码
        String randomCode = RandomStringUtils.randomNumeric(6);

//        //2.调用手机验证码模板发送手机验证码
//        smsTemplate.sendSms(phone, randomCode);

        //3.将验证码缓存到Redis中,方便后续比对校验
        redisTemplate.opsForValue().set("CHECK_CODE_"+phone,randomCode, Duration.ofMinutes(5));

       
    }
}

posted @ 2022-10-30 11:47  给我手牵你走  阅读(192)  评论(0编辑  收藏  举报