前言
这个没什么难点就是复制示例代码用就行了,重点还是申请签名和模板比较麻烦,这部分在腾讯云控制台里操作
1.service层
package com.guli.service.impl;import com.guli.service.SmsService;import com.guli.utils.SmsUtils;import com.tencentcloudapi.common.Credential;import com.tencentcloudapi.sms.v20210111.SmsClient;import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;import org.springframework.stereotype.Service;@Servicepublic class SmsServiceImpl implements SmsService {/*** 发送短信,详细设置查看test类** @param phone* @param sixBitRandom* @return*/@Overridepublic Boolean send(String phone, String sixBitRandom) {try {/* 必要步骤:* 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey*/Credential cred = new Credential(SmsUtils.SECRET_ID, SmsUtils.SECRET_KEY);/* 实例化要请求产品(以sms为例)的client对象,第二个参数是地域信息*/SmsClient client = new SmsClient(cred, SmsUtils.REGION);/* 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数*/SendSmsRequest req = new SendSmsRequest();/* 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId,示例如1400006666 */// 应用 ID 可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看String sdkAppId = "xxxxxx";req.setSmsSdkAppId(sdkAppId);/* 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名 */// 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看String signName = "xxxxx";req.setSignName(signName);/* 模板 ID: 必须填写已审核通过的模板 ID */// 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看String templateId = "xxxxx";req.setTemplateId(templateId);/* 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,若无模板参数,则设置为空 */String[] templateParamSet = {sixBitRandom, "5"};req.setTemplateParamSet(templateParamSet);/* 下发手机号码,采用 E.164 标准,+[国家或地区码][手机号]* 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号 */phone = "+86" + phone;String[] phoneNumberSet = {phone};req.setPhoneNumberSet(phoneNumberSet);/* 通过 client 对象调用 SendSms 方法发起请求。注意请求方法名与请求对象是对应的* 返回的 res 是一个 SendSmsResponse 类的实例,与请求对象对应 */SendSmsResponse res = client.SendSms(req);// 输出json格式的字符串回包System.out.println(SendSmsResponse.toJsonString(res));} catch (Exception e) {e.printStackTrace();return false;}return true;}}
2.controller
package com.guli.controller;import com.guli.commonUtils.R;import com.guli.service.SmsService;import com.guli.utils.RandomUtil;import com.mysql.cj.util.StringUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.web.bind.annotation.*;import java.util.concurrent.TimeUnit;@RestController@CrossOrigin@RequestMapping("/eduSms")public class SmsController {@Autowiredprivate SmsService smsService;@Autowiredprivate RedisTemplate<String, String> redisTemplate;/*** 向手机号发送短信** @param phone* @return*/@GetMapping("send/{phone}")public R sendSms(@PathVariable String phone) {//1.如果redis中存在,就直接返回String code = redisTemplate.opsForValue().get(phone);if (!StringUtils.isNullOrEmpty(code)) {return R.ok().message("验证码已存在");}//2.如果redis中不存在,就发送验证码//随机生成验证码,RandomUtil是自己写的工具类String sixBitRandom = RandomUtil.getSixBitRandom();Boolean isSend = smsService.send(phone, sixBitRandom);if (isSend) {//将验证码存入redis,并设置超时为5分钟redisTemplate.opsForValue().set(phone, sixBitRandom, 5, TimeUnit.MINUTES);return R.ok().message("验证码发送成功");} else {return R.error().message("验证码发送失败");}}}
3.随机数工具类
package com.guli.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>();// 生成随机数字并存入HashMapfor (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;}}
4.配置信息
package com.guli.utils;import lombok.Data;import org.springframework.beans.factory.InitializingBean;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;/*** 常量类,注入配置文件属性* 用spring的 InitializingBean 的 afterPropertiesSet 来初始化配置信息(将私有的变量值给常量以供其他类使用),* 这个方法将在所有的属性被初始化后调用*/@Component@ConfigurationProperties(prefix = "qclound.cos.file")@Datapublic class SmsUtils implements InitializingBean {private String secretId; //从配置文件中读取的腾讯云idprivate String secretKey;//从配置文件中读取的腾讯云密钥private String region;//从配置文件中读取的腾讯云地域信息public static String REGION;public static String SECRET_KEY;public static String SECRET_ID;@Overridepublic void afterPropertiesSet() throws Exception {SECRET_ID = this.secretId;SECRET_KEY = this.secretKey;REGION = this.region;}}
