当前位置:网站首页>21: Chapter 3: develop pass service: 4: further improve [send SMS, interface]; (in [send SMS, interface], call Alibaba cloud SMS service and redis service; a design idea: basecontroller;)
21: Chapter 3: develop pass service: 4: further improve [send SMS, interface]; (in [send SMS, interface], call Alibaba cloud SMS service and redis service; a design idea: basecontroller;)
2022-06-27 10:59:00 【Small withered forest】
explain :
(1) Statement :
● This project , The front end will not be deployed by itself ;;; Use your own browser or postman Test interface ;;; however , For each interface , Performance on the front page , I will explain clearly ;;; meanwhile , If I meet some “ Things that can only be made clear on the front page ”, I will also explain the context clearly ;
● The most important thing is to clear your mind ;
● Due to Alibaba cloud SMS service , Limit the maximum number of messages sent by the same mobile number in a day 10 Short message ;;; therefore , After ensuring that the Alibaba cloud SMS service has been tuned , When testing in the development phase , I usually comment out the statement that calls alicloud SMS service ;( SMS Limited , And cherish it ~~)
Catalog
zero : The rational explanation of this blog ;
zero : The rational explanation of this blog ;
1. stay 【19: The third chapter : Developing a pass service :2: In the program , Get through Alibaba cloud SMS service ;】, We got through the Alibaba cloud SMS service in the program ;
(1) First , We are 【imooc-news-dev-common】 In general engineering , Write a 【 Call alicloud SMS service , Send a text message 】 Tool class of :SMSUtils;;; natural , Other places that need to use Alibaba cloud SMS services ( such as 【imooc-news-dev-user】 This user microservice ) You can call this tool class ;
(2) then , stay 【imooc-news-dev-user】 This user microservice that needs to call alicloud SMS service , We write 【 Send a text message , Interface 】, To call SMSUtils Tool class ;
● First , stay 【imooc-news-dev-api】 Interface engineering , Defined a 【 Send a text message , Interface 】getSMSCode();
● then , stay 【imooc-news-dev-user】 In this user's microservice , To implement this interface ;
(3) At that time, the main purpose was to test whether Alibaba cloud's SMS service OK, So the interface is very simple , Not strictly in accordance with “ The front end and the back end agree ” To write ;
2. stay 【20: The third chapter : Developing a pass service :3: In the program , Get through redis The server ;】 in , We got through in the program redis The server ;
(1) First , We are 【imooc-news-dev-common】 In general engineering , Write a 【 operation redis】 Tool class of :RedisOperator;;; In this class , We have written many operations ourselves redis Methods ;;; natural , Other needs redis The place to serve ( such as 【imooc-news-dev-user】 This user microservice ) You can call this tool class ;
(2) then , stay 【imooc-news-dev-user】 This needs to use redis In the user microservices of , We are in the configuration file , To configure redis Server's url、 user name 、 Password and so on ;
(3) then , stay 【imooc-news-dev-user】 This needs to use redis In the user microservices of , What we are testing HelloController in , Write an interface , To measure redis whether OK;
(4) At that time, the main purpose was to test whether our program could be connected redis, So we are in a pure test interface , Tested it ;
3. This blog , Is to perfect 【imooc-news-dev-user】 In this user microservice ,【 Send a text message , Interface 】getSMSCode();
Let this SMS interface , Improve the logic of calling alicloud SMS services , At the same time, add the call redis Logic of service ;
One : perfect 【imooc-news-dev-user】( In this user's microservice ) Of 【 Send a text message , Interface 】getSMSCode();
1. First , perfect 【 Send a text message , Interface 】 The definition of ;( That is, improve the interface , stay 【imooc-news-dev-api】 Definition in interface engineering )
package com.imooc.api.controller.user; import com.imooc.grace.result.GraceJSONResult; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; @Api(value = " User registration login ",tags = {" The user registers to log in controller"}) @RequestMapping("passport") public interface PassportControllerApi { /** * Get SMS verification code * @param mobile: When calling this interface , You need to send your mobile number ; * @param request: We inject here HttpServletRequest, Users can be obtained through it ip; * @return */ @ApiOperation(value = " Get SMS verification code ", notes = " Get SMS verification code ", httpMethod = "GET") // The request interface on the front end is already “getSMSCode” 了 , So I am writing back-end interface url When , Don't write ; @GetMapping("/getSMSCode") public GraceJSONResult getSMSCode(@RequestParam("mobile") String mobile, HttpServletRequest request); }explain :
(1) Modify the content description ;
(2) Because in practice , When the front end requests this interface , Its integrity url yes 【/passport/getSMSCode?mobile=' + mobile】;
● therefore , This interface needs to be set url, To be consistent with the front end ; meanwhile , We also need to receive front-end parameters mobile;
● Statement : Actually , I didn't deploy the front end ( Mainly lazy , Be afraid of trouble ); I want to put more energy into the back end ;; therefore , When you are testing the back-end interface of the machine , It's just postman Or tested on the browser ;;;; however , For each interface , Performance on the front page , I will make myself clear ;;; and , Meet some “ Things that can only be made clear on the front page ”, I will also explain the context clearly ;
● then , We are here to achieve 【 The same user , stay 60 Seconds , Cannot send verification code repeatedly 】 Purpose ;;; here , It's through ip Address to determine whether it belongs to the same user ;;; therefore , We injected HttpServletRequest This method parameter ;;
2. then , perfect 【imooc-news-dev-user】( In this user's microservice ) Of 【 SMS verification code interface getSMSCode()】 The implementation of the ;
package com.imooc.user.controller; import com.imooc.api.BaseController; import com.imooc.api.controller.user.PassportControllerApi; import com.imooc.grace.result.GraceJSONResult; import com.imooc.utils.IPUtil; import com.imooc.utils.SMSUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; @RestController public class PassportController extends BaseController implements PassportControllerApi { final static Logger logger = LoggerFactory.getLogger(PassportController.class); @Autowired private SMSUtils smsUtils;// Inject , We wrote it ourselves , Alibaba cloud SMS service tools ; /** * Get SMS verification code * @return */ @Override public GraceJSONResult getSMSCode(String mobile, HttpServletRequest request) { // According to the user ip, Limit users to 60 Seconds , Only one verification code can be obtained ; String userIp = IPUtil.getRequestIp(request);// Call the tool class , Based on current request , Get users ip; redisOperator.setnx60s(MOBILE_SMSCODE + ":" + userIp, userIp);// towards redis Stores the current user requested ip, But come here 60 Seconds later , This data will time out and disappear ; String randomCode = (int) ((Math.random() * 9 + 1) * 100000) + "";// Random verification code ,6 Bit or 4 All positions are OK smsUtils.sendSMS(mobile, randomCode); // Back end , Generated 、 Native verification code , There is redis in ; Back , When the user enters the verification code at the front end , Can be used to verify ; redisOperator.set(MOBILE_SMSCODE + ":" + mobile, randomCode, 30 * 60); return GraceJSONResult.ok(); } }explain :
(1) Modify the content description ;
(2) according to HttpServletRequest Get the ip Address ;
● IPUtil Tool class : For the content in this tool class , For the time being, we can not go deep into ; meanwhile , You can see that we do not use this tool class IoC management , And the methods , We set it as static;( A lingering question : For a tool class , When is it recommended to use IoC management , When not recommended IoC management ???)
package com.imooc.utils; import javax.servlet.http.HttpServletRequest; /** * Users get users ip Tool class of */ public class IPUtil { /** * Get request IP: * The reality of users IP Out of commission request.getRemoteAddr() * This is because some agent software may be used , such ip The acquisition is not accurate * In addition, if we use multiple levels (LVS/Nginx) In the case of reverse proxy ,ip Need from X-Forwarded-For Get the first non unknown Of IP Is the user's effective ip. * @param request * @return */ public static String getRequestIp(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; } }(3) A design idea : stay 【api】 Interface engineering , Define a BaseController, In this BaseController in , Inject some ( Other microservices that handle specific business Controller in , The probability will be used ) object ;;; then , Other microservices that handle specific business Controller, You can inherit this BaseController;;; So dependent on , These microservices that handle specific businesses Controller, When you want to use certain objects , There is no need to inject again ;
● Why? BaseController Don't use IoC Container management ? For two reasons :(1) If BaseController Use IoC If containers are managed , We need to be in PassportController In the injection BaseController, Such a move is not elegant , It's not as good as the above inheritance ;;(2) When a subclass inherits a parent class , Create subclass objects , Will create a parent object ???
(4) Put the user's ip, Deposit in redis in ;(PS: It seems that I heard redis The expiration time of the median , Sometimes it's not very accurate ……, therefore , This solution , It is open to question. …… In their own actual development , This use redis Solutions to business problems by expiration time , Choose carefully !)
● Suppose the user's ip yes 【192.147.43.3】, So just make sure we store it in redis Medium key yes 【mobile_smscode:192.147.43.3】, That is, as long as this key Is unique and has ip Information is enough ;;;; Its value Is it 【192.147.43.3】 still 【“aahldjfsjk”】 It doesn't matter ;;;;; because , as long as redis There is key by 【mobile_smscode:192.147.43.3】 This data of , If the same user is 60 When a request is initiated again within , To redis When storing data in , You will find redis Already there are key by 【mobile_smscode:192.147.43.3】 The data of the ,,, It is determined that the same user wants to 60 Repeat the call within seconds , It's natural to be rejected ;
(5) Backstage , Randomly generate a verification code ;( This is very simple , There's nothing to say )
(6) Call alicloud SMS service , Go to the verification code generated in the background , Send it to the user in the form of SMS ;
(7) then , Save our generated verification code to redis in ;( Back , When the user inputs the received verification code at the front end , We will reduce the 【 After the user receives the message , The verification code entered on the front page 】 and 【redis The native verification code stored in 】 compare )
Two : effect ;
(1) First , overall situation install once ;
(2) then , start-up 【user】 The main startup class of ;
(3) then , visit 【user】 Of 【"/getSMSCode"】 Interface ;
边栏推荐
- If you find any loopholes later, don't tell China!
- 【TcaplusDB知识库】TcaplusDB Tmonitor模块架构介绍
- Oracle连接MySQL报错IM002
- The tutor invites you to continue your doctoral study with him. Will you agree immediately?
- 以后发现漏洞,禁止告诉中国!
- 飞桨产业级开源模型库:加速企业AI任务开发与应用
- LeetCode 522 最长特殊序列II[枚举 双指针] HERODING的LeetCode之路
- Brother sucks 590000 fans with his unique "quantum speed reading" skill: look at the street view for 0.1 seconds, and "snap" can be accurately found on the world map
- Quelles sont les fonctions de base nécessaires au développement d'applications de commerce électronique en direct? Quelles sont les perspectives d'avenir?
- Support system of softswitch call center system
猜你喜欢
随机推荐
Based on swift admin's rapid background development framework, I made a rookie tutorial [professional version]
Flutter wechat sharing
Audiotrack and audiolinker
Leetcode 729. 我的日程安排表 I(提供一种思路)
Introduction to the use of Arduino progmem static storage area
上周热点回顾(6.20-6.26)
Go zero micro Service Practice Series (VII. How to optimize such a high demand)
Working at home is more tiring than going to work at the company| Community essay solicitation
微软云 (Microsoft Cloud) 技术概述
Installation manuelle de MySQL par UBUNTU
In the three-tier architecture, at which layer is the database design implemented, not at the data storage layer?
[tcapulusdb knowledge base] Introduction to tmonitor background one click installation (I)
20 jeunes Pi recrutés par l'Institut de microbiologie de l'Académie chinoise des sciences, 2 millions de frais d'établissement et 10 millions de fonds de démarrage (à long terme)
Oracle trigger stored procedure writes at the same time
21:第三章:开发通行证服务:4:进一步完善【发送短信,接口】;(在【发送短信,接口】中,调用阿里云短信服务和redis服务;一种设计思想:BaseController;)
TCP/IP 详解(第 2 版) 笔记 / 3 链路层 / 3.4 桥接器与交换机 / 3.4.1 生成树协议(Spanning Tree Protocol (STP))
在外企远程办公是什么体验? | 社区征文
【TcaplusDB知识库】TcaplusDB机器初始化和上架介绍
Future & CompletionService
Go zero micro Service Practice Series (VII. How to optimize such a high demand)






























