1.開通服務
2.申請簽名管理和模闆管理
3.添加依賴
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
</dependency>
</dependencies>
4.配置檔案
# 服務端口
server.port=8005
# 服務名
spring.application.name=service-msm
# mysql資料庫連接配接
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/guli?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
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
#最小空閑
#傳回json的全局時間格式
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
#mybatis日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
5.整合短信服務
随機數工具類
package com.tjk.msmservice.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 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));
}
/**
* 給定數組,抽取n個資料
* @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>();
// 生成随機數字并存入HashMap
for (int i = 0; i < list.size(); i++) {
int number = random.nextInt(100) + 1;
hashMap.put(number, i);
}
// 從HashMap導入數組
Object[] robjs = hashMap.values().toArray();
ArrayList r = new ArrayList();
// 周遊數組并列印資料
for (int i = 0; i < n; i++) {
r.add(list.get((int) robjs[i]));
System.out.print(list.get((int) robjs[i]) + "\t");
}
System.out.print("\n");
return r;
}
}
發送短信
Service
public class MsmServiceImpl implements MsmService {
@Override
public boolean send(HashMap<String, Object> map, String phone) {
if(StringUtils.isEmpty(phone)) return false;
DefaultProfile profile =
DefaultProfile.getProfile("default", "Yourskey", "Yourkeysecret");
IAcsClient client = new DefaultAcsClient(profile);
//設定相關固定的參數
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");
//設定發送相關的參數
request.putQueryParameter("PhoneNumbers",phone); //手機号
request.putQueryParameter("SignName","申請阿裡雲 簽名名稱"); //申請阿裡雲 簽名名稱
request.putQueryParameter("TemplateCode","模闆code"); //申請阿裡雲 模闆code
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map)); //驗證碼資料,轉換json資料傳遞
try {
//最終發送
CommonResponse response = client.getCommonResponse(request);
boolean success = response.getHttpResponse().isSuccess();
return success;
}catch(Exception e) {
e.printStackTrace();
return false;
}
}
}
驗證碼5分鐘有效
@RestController
@CrossOrigin
@RequestMapping("/edumsm/msm")
public class MsmController {
@Autowired
private MsmService msmService;
@Autowired
private RedisTemplate<String,String> redisTemplate;
@GetMapping("send/{phone}")
public R sendMsm(@PathVariable String phone){
//1. 從redis中擷取驗證碼,如果有直接傳回
String code = redisTemplate.opsForValue().get(phone);
if(!StringUtils.isEmpty(code)){
return R.ok();
}
//如果沒有就向阿裡雲發送請求
//生成随機值,傳遞阿裡雲進行發送
code= RandomUtil.getFourBitRandom();
HashMap<String, Object> map = new HashMap<>();
map.put("code",code);
boolean isSend= msmService.send(map,code);
if(isSend){
//發送成功 把發送成功驗證碼放到redis裡面
//設定有效時間
redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
return R.ok();
}else {
return R.error().message("短信發送失敗");
}
}
}