0. Source code address
Github.com/tzforeveree…
1. The technology stack
- java
- springboot
- maven
- redis
2. Enter the official website of Aliyun
www.aliyun.com/
2.1 Login => Enter the SMS service
2.2 Enabling services => Access the management console
Note: I have already opened the service, so this shows the administrative console
2.3 Adding A Template
Choose National Message > Template Management > Add Template
Click Add Template to enter the add page and enter the template information
- Select template type: Verification code
- Template name: XXXXX (must have specific meaning, otherwise the audit will not pass)
- Template content: Common template libraries are available below the input box
- Application Instructions: XXXX (with specific instructions)
Click Submit and wait for approval. After approval, you can use it
2.4 Adding Signature Management
Choose National Message – Signature Management – Add Signature
Click Add Signature, enter the add page, fill in the relevant information Note: the signature should be written with practical meaning
- The signature
- Usage scenarios
- Application Instructions: Do not write
Click Submit and wait for approval. After approval, you can use it
2.5 Pay attention to your Own Accesskey
Save your own AccessKeyID and AccessKeySecret
3. Initialize the project
3.1 Creating an empty Maven project
3.2 Adding project dependencies
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> < version > 2.2.1. RELEASE < / version > < / dependency > < the dependency > < groupId > com. Alibaba < / groupId > <artifactId>fastjson</artifactId> <version>1.2.28</version> </dependency> <dependency> <groupId>com.aliyun</groupId> < artifactId > aliyun - Java - SDK - core < / artifactId > < version > 4.3.3 < / version > < / dependency > <! Lombok uses to simplify entity classes: Lombok <dependency> <groupId>org.projectlombok</groupId> <artifactId> Lombok </artifactId> <version>1.18.10</version> <scope>provided </scope> </dependency> <! -- redis --> <dependency> <groupId>org.springframework.boot</groupId> < artifactId > spring - the boot - starter - data - redis < / artifactId > < version > 2.2.1. RELEASE < / version > < / dependency > < the dependency > Mons < groupId > org.apache.com < / groupId > < artifactId > Commons - pool2 < / artifactId > < version > 2.7.0 < / version > < / dependency > </dependencies>Copy the code
3.3 create application. The properties
Server.port =8001 spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.database= 0 spring.redis.timeout=1800000 spring.redis.lettuce.pool.max-active=20 spring.redis.lettuce.pool.max-wait=-1 spring.redis.lettuce.pool.max-idle=5 spring.redis.lettuce.pool.min-idle=0 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.time-zone=GMT+8Copy the code
3.4 Creating an Initiator AliApplication
@ SpringBootApplication (exclude = DataSourceAutoConfiguration. Class) / / avoid not connect to the database error public class AliApplication {public static void main(String[] args) { SpringApplication.run(AliApplication.class,args); }}Copy the code
3.5 Creating an Interface Definition Return Code
public interface ResultCode {
public static Integer SUCCESS = 20000;
public static Integer ERROR = 20001;
}Copy the code
3.5 Creating a Unified Result Return Class
@data public class R {private Boolean success; // Return code private Integer code; // Return message private String message; Private Map<String, Object> data = new HashMap<String, Object>(); private R(){}; public static R ok(){ R r = new R(); r.setSuccess(true); r.setCode(ResultCode.SUCCESS); R.s etMessage (" success "); return r; } public static R error(){ R r = new R(); r.setSuccess(true); r.setCode(ResultCode.ERROR); R.s etMessage (" failure "); return r; } public R success(Boolean success){ this.setSuccess(success); return this; } public R message(String message){ this.setMessage(message); return this; } public R code(Integer code){ this.setCode(code); return this; } public R data(String key, Object value){ this.data.put(key, value); return this; } public R data(Map<String, Object> map){ this.setData(map); return this; }Copy the code
3.6 Create RandomUtil under utils package
package com.demo.aliservice.utils; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Random; /** * @author qianyi ** / public class RandomUtil {private static final Random = new Random(); private static final DecimalFormat fourdf = new DecimalFormat("0000"); private static final DecimalFormat sixdf = new DecimalFormat("000000"); public static String getFourBitRandom() { return fourdf.format(random.nextInt(10000)); } public static String getSixBitRandom() { return sixdf.format(random.nextInt(1000000)); } /** * given an array, * @param list * @param n * @return */ public static ArrayList getRandom(list list, int n) { Random random = new Random(); HashMap<Object, Object> hashMap = new HashMap<Object, Object>(); // Generate random numbers and store them in HashMap for (int I = 0; i < list.size(); i++) { int number = random.nextInt(100) + 1; hashMap.put(number, i); } // Import array Object from HashMap [] robjs = hashmap.values ().toarray (); ArrayList r = new ArrayList(); For (int I = 0; i < n; i++) { int position = Integer.parseInt(String.valueOf(robjs[i])); r.add(list.get(position)); } return r; }}Copy the code
3.7 Creating servie Interface and Service implementation classes
The service interface
public interface AliService {
boolean send(Map<String, Object> param, String phone);
}Copy the code
Service is implemented
@Service public class AliServiceImpl implements AliService { public boolean send(Map<String, Object> param, String phone) { if(StringUtils.isEmpty(phone)) return false; /** AccessKeySecret: **/ DefaultProfile profile = DefaultProfile.getProfile("default", "LTAaASQDF1CGTEEFGUXZHMA", "WRTSbya6qe1SDS6qwe13aWSH0"); IAcsClient client = new DefaultAcsClient(profile); // Set the related fixed parameters CommonRequest request = new CommonRequest(); //request.setProtocol(ProtocolType.HTTPS); request.setMethod(MethodType.POST); request.setDomain("dysmsapi.aliyuncs.com"); request.setVersion("2017-05-25"); request.setAction("SendSms"); / / set the request send related parameters. PutQueryParameter (" PhoneNumbers, phone); / / phone number request. PutQueryParameter (" SignName ", "my XXX online website"); / / apply for ali cloud signature name request. PutQueryParameter (" TemplateCode, "" SMS_139315701"); / / apply for ali cloud template code request. PutQueryParameter (" TemplateParam ", JSONObject. ToJSONString (param)); CommonResponse Response = client.getCommonResponse(request); boolean success = response.getHttpResponse().isSuccess(); return success; }catch(Exception e) { e.printStackTrace(); return false; }}}Copy the code
3.8 Creating a Controller Controller
@RestController @RequestMapping("/msm") public class AliController { @Autowired private AliService aliService; @Autowired private RedisTemplate<String,String> redisTemplate; @GetMapping("send/{phone}") public R sedMsm(@PathVariable String phone){ // 1. Obtain verification code from the redis, get less than sending a String code1. = redisTemplate opsForValue () get (phone); if(! StringUtils.isEmpty(code1)){ return R.ok(); } / / generate random values, sends a String code = RandomUtil. Ali cloud transmitted getFourBitRandom (); Map<String,Object> param = new HashMap<String,Object>(); param.put("code",code); boolean isSend = aliService.send(param,phone); If (isSend) {/ / sent successfully, the successful validation to redis pattern, and set up effective time redisTemplate. OpsForValue (). The set (phone, code, 5, TimeUnit. MINUTES); return R.ok(); }else{return r.ror ().message(" SMS failed to send "); }}}Copy the code
3.9 Overall project structure
4. Run the code and debug using Postman
Received message:
This article is published by OpenWrite, a blogging tool platform