具体那些需要怎么去申请key这些的我就不说了请百度 直接上代码
1.POM依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<dependency>
<groupId>org.messaginghub</groupId>
<artifactId>pooled-jms</artifactId>
<version>1.1.0</version>
</dependency>
<!--消息队列连接池-->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.1.0</version>
</dependency>
<!-- 检验数据StringUtis -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
2.YAML配置文件
server:
port: 7788
spring:
application:
name: smsService
redis:
database: 3
host: ********************
port: 6379
password: ********************
jedis:
pool:
max-active: 8
max-idle: 8
min-idle: 0
# 消息队列
activemq:
user: system
password: manager
broker-url: tcp://********************
jms:
pub-sub-domain: false # 如果需要topic模式需要改为false
accessKeyId:********************
accessKeySecret:********************
# 注册中心配置
eureka:
instance:
prefer-ip-address: true
instance-id: ${spring.cloud.client.ip-address}:${server.port}
client:
service-url:
defaultZone: http://localhost:10086/eureka/
3.编写枚举类Sms存放模板和签名
public enum Sms {
TEMPLATE_CODE("TemplateCode", "SMS_195871321"),
SING_NAME("signName", "信查查");
Sms(String code, String desc) {
this.name = code;
this.value = desc;
}
private final String name;
private final String value;
public String getName() {
return name;
}
public String getValue() {
return value;
}}
4.编写Listener监听器
@Component
public class SmsListener {
@Autowired
private SmsUtils smsUtil;
//使用监听器进行消息的监听操作 ,将消息发送过来,进行短信发送
@JmsListener(destination = "sms")
public void sendSms(Map<String,String> map) {
// RespBean respBean = null;
try {
System.out.println(map.toString());
SendSmsResponse response = smsUtil.sendSms(
map.get("mobile"),
map.get("TemplateCode"),
map.get("signName"),
map.get("param")
);
System.out.println("Code=" + response.getCode());
System.out.println("Message=" + response.getMessage());
System.out.println("RequestId=" + response.getRequestId());
System.out.println("BizId=" + response.getBizId());
} catch (ClientException e) {
e.printStackTrace();
}
}
}
5.编写SmsUtils工具类
package com.zyyx.xcc.sms_service.utils;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
/**
* @ClassName SmsUtils
* @Description TODO
* @Author ZhangSan_Plus
* @Date 2020/6/4 17:19
* @Version 1.0
**/
@PropertySource("classpath:application.yml")//在加载钥密
@Component
public class SmsUtils {
//产品名称:云通信短信API产品,开发者无需替换
static final String product = "Dysmsapi";
//产品域名,开发者无需替换
static final String domain = "dysmsapi.aliyuncs.com";
private static final String SYMBOLS = "0123456789"; // 数字
private static final Random RANDOM = new SecureRandom();
@Autowired
private Environment env;
/**
* 发送短信
*
* @param mobile 手机号
* @param template_code 模板号
* @param sign_name 签名
* @param param 参数
* @return
* @throws ClientException
*/
public SendSmsResponse sendSms(String mobile, String template_code, String sign_name, String param) throws ClientException {
// TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
String accessKeyId = env.getProperty("accessKeyId");
String accessKeySecret = env.getProperty("accessKeySecret");
//可自助调整超时时间
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
//初始化acsClient,暂不支持region化
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
IAcsClient acsClient = new DefaultAcsClient(profile);
//组装请求对象-具体描述见控制台-文档部分内容
SendSmsRequest request = new SendSmsRequest();
//必填:待发送手机号
request.setPhoneNumbers(mobile);
//必填:短信签名-可在短信控制台中找到
request.setSignName(sign_name);
//必填:短信模板-可在短信控制台中找到
request.setTemplateCode(template_code);
//可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
request.setTemplateParam("{\"code\":\"" + param + "\"}");
//选填-上行短信扩展码(无特殊需求用户请忽略此字段)
//request.setSmsUpExtendCode("90997");
//可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
request.setOutId("yourOutId");
//hint 此处可能会抛出异常,注意catch
SendSmsResponse sendSmsResponse = null;
try {
sendSmsResponse = acsClient.getAcsResponse(request);
} catch (Exception e) {
e.printStackTrace();
}
return sendSmsResponse;
}
/**
* 消息查询响应
*
* @param mobile 电话号码
* @param bizId
* @return
* @throws ClientException
*/
public QuerySendDetailsResponse querySendDetails(String mobile, String bizId) throws ClientException {
String accessKeyId = env.getProperty("accessKeyId");
String accessKeySecret = env.getProperty("accessKeySecret");
//可自助调整超时时间
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
//初始化acsClient,暂不支持region化
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
IAcsClient acsClient = new DefaultAcsClient(profile);
//组装请求对象
QuerySendDetailsRequest request = new QuerySendDetailsRequest();
//必填-号码
request.setPhoneNumber(mobile);
//可选-流水号
request.setBizId(bizId);
//必填-发送日期 支持30天内记录查询,格式yyyyMMdd
SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
request.setSendDate(ft.format(new Date()));
//必填-页大小
request.setPageSize(10L);
//必填-当前页码从1开始计数
request.setCurrentPage(1L);
//hint 此处可能会抛出异常,注意catch
QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);
return querySendDetailsResponse;
}
/**
* @param type 输入4/6 生成4位或者6位的验证码
* @return
*/
public static String getVerificationCode(Integer type) {
char[] nonceChars = new char[type];
for (int index = 0; index < nonceChars.length; ++index) {
nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
}
return new String(nonceChars);
}
}
6.编写SmsService
import com.search.basics.pojo.RespBean;
/**
* @ClassName SmsService
* @Description TODO
* @Author ZhangSan_Plus
* @Date 2020/6/5 16:54
* @Version 1.0
**/
public interface SmsService {
RespBean sendSms(String phone);
}
7.编写SmsService 实现类SmsServiceImpl
package com.zyyx.xcc.sms_service.service.impl;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.search.basics.pojo.RespBean;
import com.zyyx.xcc.sms_service.config.Sms;
import com.zyyx.xcc.sms_service.service.SmsService;
import com.zyyx.xcc.sms_service.utils.SmsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @ClassName SmsServiceImpl
* @Description TODO
* @Author ZhangSan_Plus
* @Date 2020/6/5 16:58
* @Version 1.0
**/
@Service
public class SmsServiceImpl implements SmsService {
//验证手机号是否正确的正则表达式 方可忽略
private static final String REGEX = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[0-3]|[5-9])|(18[0,5-9])|(19[0,5-9]))\\d{8}$";
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private SmsUtils smsUtil;
@Override
public RespBean sendSms(String phone) {
RespBean respBean = null;
System.out.println(phone);
if (phone.length() != 11) {
respBean = RespBean.error("输入手机号不正确");
}
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(phone);
boolean isMatch = m.matches();
if (isMatch) {
Map<String, String> map = new HashMap<>();
String verificationCode = SmsUtils.getVerificationCode(6);
map.put("mobile", phone);
map.put(Sms.SING_NAME.getName(), Sms.SING_NAME.getValue());
map.put(Sms.TEMPLATE_CODE.getName(), Sms.TEMPLATE_CODE.getValue());
map.put("param", verificationCode);
//将手机号放入redis 并设置5分钟的失效时间
stringRedisTemplate.opsForValue().set(phone, verificationCode, 60 * 5, TimeUnit.SECONDS);
jmsMessagingTemplate.convertAndSend("sms", map);
try {
SendSmsResponse response = smsUtil.sendSms(
map.get("mobile"),
map.get("TemplateCode"),
map.get("signName"),
map.get("param")
);
if (!"OK".equals(response.getMessage())) {
//阿里云短信具有流控:一分钟1次,一小时5次,一天10次 请注意官方以说明
if (response.getMessage().equals("触发分钟级流控Permits:1")) {
respBean = RespBean.ok("短信发送成功");
} else {
respBean = RespBean.error(400, response.getMessage());
}
} else {
respBean = RespBean.ok("短信发送成功");
}
} catch (ClientException e) {
e.printStackTrace();
}
}
return respBean;
}
}
编写Controller调用SmsService 即可!