springboot异步发送短信
时间: 2023-08-16 18:05:01 浏览: 87
可以使用Spring Boot提供的异步支持来发送短信。
首先,在pom.xml文件中添加如下依赖:
```xml
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.5.3</version>
</dependency>
```
然后,创建一个短信发送服务类,如下所示:
```java
@Service
public class SmsService {
private static final Logger logger = LoggerFactory.getLogger(SmsService.class);
@Autowired
private AliyunSmsProperties aliyunSmsProperties;
@Async
public void sendSms(String phoneNumber, String message) {
try {
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", aliyunSmsProperties.getAccessKeyId(),
aliyunSmsProperties.getAccessKeySecret());
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", aliyunSmsProperties.getProduct(),
aliyunSmsProperties.getDomain());
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.setMethod(MethodType.POST);
request.setDomain(aliyunSmsProperties.getDomain());
request.setVersion(aliyunSmsProperties.getVersion());
request.setAction("SendSms");
request.putQueryParameter("PhoneNumbers", phoneNumber);
request.putQueryParameter("SignName", aliyunSmsProperties.getSignName());
request.putQueryParameter("TemplateCode", aliyunSmsProperties.getTemplateCode());
request.putQueryParameter("TemplateParam", "{\"message\":\"" + message + "\"}");
CommonResponse response = client.getCommonResponse(request);
logger.info("短信发送结果: " + response.getData());
} catch (Exception e) {
logger.error("短信发送失败: " + e.getMessage());
}
}
}
```
其中,AliyunSmsProperties用于存储阿里云短信服务的配置信息,如下所示:
```java
@Component
@ConfigurationProperties(prefix = "aliyun.sms")
public class AliyunSmsProperties {
private String accessKeyId;
private String accessKeySecret;
private String product;
private String domain;
private String version;
private String signName;
private String templateCode;
// 省略getter和setter方法
}
```
最后,在需要发送短信的地方,注入SmsService并调用sendSms方法即可,如下所示:
```java
@Autowired
private SmsService smsService;
public void sendMessage(String phoneNumber, String message) {
smsService.sendSms(phoneNumber, message);
}
```
需要注意的是,sendSms方法使用了@Async注解,表示该方法是一个异步方法,会在新的线程中执行,以避免阻塞主线程。同时,需要在Spring Boot的配置类中添加@EnableAsync注解来启用异步支持。
阅读全文