SpringBoot项目中使用Redis整合阿里云短信服务
程序员文章站
2022-05-15 14:13:38
...
1、引入相关依赖
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-ecs</artifactId>
<version>4.17.6</version>
</dependency>
2、目录结构
application.yml
server:
port: 8005
spring:
application:
name: service-msm
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
redis:
host: 192.168.61.xxx
port: 6379
database: 0
timeout: 1800000ms
lettuce:
pool:
max-active: 20
max-wait: -1ms
max-idle: 5
min-idle: 0
msm:
access-key: LTAI4G8q7nBEsUc2i
access-secret: 3FEJ5vh5EdVjuvUWdt5
sys-domain: dysmsapi.aliyuncs.com
sys-version: 2017-05-25
sys-action: SendSms
sign-name: 坤爷商城
template-code: SMS_180355450
MsmConfig
@Component
@ConfigurationProperties(prefix = "msm")
@Data
public class MsmConfig {
private String regionId;
private String accessKey;
private String accessSecret;
private String sysDomain;
private String sysVersion;
private String sysAction;
private String signName;
private String templateCode;
}
MsmController
@RestController
@RequestMapping("/msm")
public class MsmController {
@Autowired
private MsmService msmService;
@Autowired
private StringRedisTemplate redisTemplate;
@GetMapping("sendMessage/{phone}")
public ResponseResult sendMessage(@PathVariable("phone") String phone) {
if (StringUtils.isBlank(phone)) {
return ResponseResult.error().message("请输入手机号码");
}
//1.从redis中获取验证码,如果获取到直接返回
String code = redisTemplate.opsForValue().get(phone);
if(StringUtils.isNotBlank(code)){
return ResponseResult.success();
}
//2.从redis中获取不到,进行阿里云发送
//生成随机值
code = RandomUtil.getSixBitRandom();
Map<String, Object> params = new HashMap<>();
params.put("code",code);
//调用service发送短信的方法
boolean isSend = msmService.sendMessage(params,phone);
if(isSend){
//短信发送成功,将验证码保存到redis
redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
return ResponseResult.success().message("短信发送成功");
}else {
return ResponseResult.error().message("短信发送失败");
}
}
}
MsmServiceImpl
@Service
public class MsmServiceImpl implements MsmService {
@Autowired
private MsmConfig msmConfig;
@Override
public boolean sendMessage(Map<String,Object> params ,String phone) {
//初始化个人信息
DefaultProfile profile = DefaultProfile.getProfile("default", msmConfig.getAccessKey(), msmConfig.getAccessSecret());
IAcsClient client = new DefaultAcsClient(profile);
//设置相关固定的参数
CommonRequest request = new CommonRequest();
request.setSysMethod(MethodType.POST);
request.setSysDomain(msmConfig.getSysDomain());
request.setSysVersion(msmConfig.getSysVersion());
request.setSysAction(msmConfig.getSysAction());
//设置发送相关的参数
// request.putQueryParameter("RegionId", msmConfig.getRegionId());
request.putQueryParameter("PhoneNumbers", phone); //手机号
request.putQueryParameter("SignName", msmConfig.getSignName()); //签名
request.putQueryParameter("TemplateCode", msmConfig.getTemplateCode());//模版CODE
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(params)); //验证码数据,要转换成json格式
try {
//最终发送
CommonResponse response = client.getCommonResponse(request);
boolean success = response.getHttpResponse().isSuccess();
return success;
} catch (ClientException e) {
e.printStackTrace();
return false;
}
}
}
最后附上生成随机验证码的工具类RandomUtil
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>();
// 生成随机数字并存入HashMap
for (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;
}
}