Java网络商城项目 SpringBoot+SpringCloud+Vue 网络商城(SSM前后端分离项目)十八(阿里短信服务,Redis限流)
Posted 蓝盒子itbluebox
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java网络商城项目 SpringBoot+SpringCloud+Vue 网络商城(SSM前后端分离项目)十八(阿里短信服务,Redis限流)相关的知识,希望对你有一定的参考价值。
在这之前需要安装Redis和有一定的基础,请看我的上一篇文章
Java 之SpringData Redis快速入门 以及( Redis快速入门安装和使用)
一、阿里短信服务
1、创建短信微服务
因为系统中不止注册一个地方需要短信发送,因此我们将短信发送抽取为微服务
ly-sms-service
,凡是需要的地方都可以使用。
另外,因为短信发送API调用时长的不确定性,
为了提高程序的响应速度,短信发送我们都将采用异步发送方式,
即:短信服务监听MQ消息,收到消息后发送短信。
·其它服务要发送短信时,通过MQ通知短信微服务。
(1)创建module
(2)引入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>leyou</artifactId>
<groupId>com.leyou.parent</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.leyou.service</groupId>
<artifactId>ly-sms</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.0.6</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.leyou.common</groupId>
<artifactId>ly-common</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
(3)编写启动类
package com.leyou;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class LySmsApplication {
public static void main(String[] args) {
SpringApplication.run(LySmsApplication.class,args);
}
}
(4)编写配置文件
server:
port: 8087
spring:
application:
name: sms-service
rabbitmq:
host: 192.168.58.101
username: leyou
password: leyou
virtual-host: /leyou
2、编写短信工具类
(1)属性抽取
我们首先把一些常量抽取到application.yml中:
ly:
sms:
accessKeyId: JWffwFJIwada #你自己的accessKeyid
accessKeySecret: aySRliswq8fe7rF9gQyy1Izz4MQ #你自己的AccessKeySecret
signName: 乐优商城 #签名名称
verifyCodeTemplate: SMS_133976814 #模板名称
编写SmsProperties类去读取配置文件
package com.leyou.sms.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@ConfigurationProperties(prefix = "ly.sms")
@Data
public class SmsProperties {
String accessKeyId;
String accessKeySecret;
String signName;
String verifyCodeTemplate;
}
(2)编写工具类
package com.leyou.sms.utils;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.leyou.sms.config.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import sun.rmi.runtime.Log;
@Slf4j
@Component
@EnableConfigurationProperties(SmsProperties.class)
public class SmsUtils {
@Autowired
private SmsProperties prop;
//产品名称:云通信短信API产品,开发者无需替换
static final String product = "Dysmsapi";
//产品域名,开发者无需替换
static final String domain = "dysmsapi.aliyuncs.com";
public SendSmsResponse sendSms(String phoneNumber, String signName, String templateCode, String templateParam) throws ClientException {
//可自助调整超时时间
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
//初始化acsClient,暂不支持region化
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", prop.getAccessKeyId(), prop.getAccessKeySecret());
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
IAcsClient acsClient = new DefaultAcsClient(profile);
//组装请求对象-具体描述见控制台-文档部分内容
SendSmsRequest request = new SendSmsRequest();
request.setMethod(MethodType.POST);
//必填:待发送手机号
request.setPhoneNumbers(phoneNumber);
//必填:短信签名-可在短信控制台中找到
request.setSignName(signName);
//必填:短信模板-可在短信控制台中找到
request.setTemplateCode(templateCode);
//可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
request.setTemplateParam(templateParam);
//hint 此处可能会抛出异常,注意catch
SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
if (!"OK".equals(sendSmsResponse.getCode())) {
log.info("[短信服务]发送短信失败,phoneNumber:{} , 失败原因 {}", phoneNumber, sendSmsResponse.getMessage());
}
return sendSmsResponse;
}
}
3、编写消息监听器
接下来,编写消息监听器,当接收到消息后,我们发送短信。
package com.leyou.sms.mq;
import com.leyou.common.utils.JsonUtils;
import com.leyou.sms.config.SmsProperties;
import com.leyou.sms.utils.SmsUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.Map;
@Component
@EnableConfigurationProperties(SmsProperties.class)
@Slf4j
public class SmsListener {
@Autowired
private SmsProperties prop;
@Autowired
private SmsUtils smsUtils;
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "sms.verify.code.queue", durable = "true"),
exchange = @Exchange(name = "ly.sms.exchange", type = ExchangeTypes.TOPIC),
key = "sms.verify.code"
))
public void listenInsertOrUpdate(Map<String,String> msg) {
if(CollectionUtils.isEmpty(msg)){
return;
}
String phone = msg.remove("phone");//remove方法删除并且获取
if(StringUtils.isBlank(phone)){
return;
}
//发送信息
try {
smsUtils.sendSms(phone,prop.getSignName(),prop.getVerifyCodeTemplate(), JsonUtils.toString(msg));
}catch (Exception e){
log.error("[短信服务]发送短信异常 手机号码{}",phone,e);
}
}
}
5、编写测试方法
package com.leyou.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.stereotype.Component;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.HashMap;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SmsTest {
@Autowired
private AmqpTemplate amqpTemplate;
@Test
public void testSend(){
Map<String,String > msg = new HashMap<>();
msg.put("phone","15245621456");
msg.put("code","54321");
amqpTemplate.convertAndSend("ly.sms.exchange","sms.verify.code",msg);
}
}
运行测试
发送成功
手机收到短信
6、通过Redis做短信的限流
(1)设置Redis的配置文件
(2)修改SmsUtils工具类
package com.leyou.sms.utils;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.leyou.sms.config.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import sun.rmi.runtime.Log;
import java.util.concurrent.TimeUnit;
@Slf4j
@Component
@EnableConfigurationProperties(SmsProperties.class)
public class SmsUtils {
@Autowired
private SmsProperties prop;
//产品名称:云通信短信API产品,开发者无需替换
static final String product = "Dysmsapi"IDEA SpringBoot 项目打包成jar包
(超详解)SpringBoot高级部分-自动配置+监听机制+监控+项目部署