import org.redisson.api.RedissonClient;
@Resource
private RedissonClient redissonClient;
public AjaxResult getSmsVerificationCode(CarrierInfoReq carrierInfoReq) {
log.info("承运商短信验证码接口传参={}", carrierInfoReq.getContactNumber());
if (StringUtils.isBlank(carrierInfoReq.getContactNumber())) {
throw new CustomException("手机号不能为空!");
}
String regex = "^1[0-9]{10}$";
boolean matches = Pattern.matches(regex, carrierInfoReq.getContactNumber());
if (!matches) {
throw new CustomException("请输入正确的手机号!");
}
String key = "scm:basedata:sms:verificationCode:" + carrierInfoReq.getContactNumber();
int min = 100000; // 6位数的最小值
int max = 999999; // 6位数的最大值
Random random = new Random();
// 6位随机验证码
int verificationCode = random.nextInt(max - min + 1) + min;
SendSmsBean sendSmsBean = new SendSmsBean();
sendSmsBean.setPhoneNumbers(carrierInfoReq.getContactNumber());
sendSmsBean.setAppName("承运商平台系统登陆");
sendSmsBean.setTemplateCode("17126");
//不可以改
sendSmsBean.setSignName("供应链");
JSONObject jsonObject = new JSONObject();
jsonObject.put("code", verificationCode);
String codeString = JSON.toJSONString(jsonObject);
sendSmsBean.setTemplateParamJson(codeString);
Map<String, Object> mapResult = new HashMap<>();
mapResult.put("timeStamp", DateUtils.getTime());
mapResult.put("contactNumber", carrierInfoReq.getContactNumber());
try {
// 从缓存里面取值验证码
String verificationCodeValue = null;
RBucket<String> bucket = redissonClient.getBucket(key);
if(bucket.isExists()){
verificationCodeValue = bucket.get();
}
if (StringUtils.isNotBlank(verificationCodeValue)) {
mapResult.put("smsVerificationCode", verificationCodeValue);
return AjaxResult.success(mapResult);
}
AjaxResult ajaxResult = smsService.sendSms(sendSmsBean);
if ("200".equals(MapUtils.getString(ajaxResult, "code", "0"))) {
// 验证码放入缓存,过期时间60秒
bucket.set(String.valueOf(verificationCode));
bucket.expire(60, TimeUnit.SECONDS); // 设置过期时间为60秒
mapResult.put("smsVerificationCode", verificationCode);
} else {
log.error("承运商短信验证码接口异常=" + ajaxResult.toString());
return AjaxResult.error("获取承运商短信验证码失败!", ajaxResult);
}
} catch (Exception e) {
log.error("承运商短信验证码接口异常=", e);
return AjaxResult.error("获取承运商短信验证码失败!", mapResult);
}
return AjaxResult.success(mapResult);
}
RedissonClient的使用
于 2023-08-16 10:55:12 首次发布
8347

被折叠的 条评论
为什么被折叠?



