Spring Boot 短信服务

本文最后更新于:2024年9月8日 晚上

Spring Boot 短信服务

pom.xml

1
2
3
4
5
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>2.0.9</version>
</dependency>

核心工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@Component
@Slf4j
public class SMSUtil {

@Resource
Client smsClient;

@Bean
public com.aliyun.dysmsapi20170525.Client smsClient() throws Exception {
Config config = new Config()
.setAccessKeyId(AliyunConfig.accessKeyId)
.setAccessKeySecret(AliyunConfig.accessKeySecret)
.setEndpoint(AliyunConfig.smsEndpoint);
return new com.aliyun.dysmsapi20170525.Client(config);
}

public boolean sendSMS(String phoneNum, String templateParam) throws Exception {
SendSmsRequest sendSmsRequest = new SendSmsRequest()
.setPhoneNumbers(phoneNum)
.setSignName("软件魔法")
.setTemplateCode("SMS_198667517")
.setTemplateParam(templateParam);
try {
return ObjectUtil.equals(smsClient.sendSms(sendSmsRequest).getBody().getMessage(), "OK");
} catch (Exception e) {
log.error("短信服务异常:{}", e.getMessage(), e);
return false;
}
}
}

整合Redis

  • pom.xml
1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  • SMSUtils
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public boolean sendVerificationCode(String phoneNum) {
BusinessPreconditions.checkArgument(ObjectUtil.isEmpty(redisUtil.get(verificationCodePrefix + phoneNum)), "请勿重复获取验证码");
// 生成验证码并存储到Redis中。
String verificationCode = RandomUtil.randomNumbers(6);
HashMap<String, Object> param = MapUtil.newHashMap();
param.put("code", verificationCode);
if (this.sendSMS(phoneNum, param)) {
return redisUtil.set(verificationCodePrefix + phoneNum, verificationCode, 300);
} else {
return false;
}
}

public boolean checkVerificationCode(String phoneNum, String verificationCode) {
String redisVerificationCode = (String) redisUtil.get(verificationCodePrefix + phoneNum);
BusinessPreconditions.checkArgument(StrUtil.isNotEmpty(verificationCode), "未获取验证码");
return ObjectUtil.equals(redisVerificationCode, verificationCode);
}