1.添加手机号验证码登录
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
package com.ruoyi.common.config;
|
||||
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.ruoyi.common.core.domain.AjaxResult;
|
||||
import com.ruoyi.common.core.domain.entity.SmsRequestDTO;
|
||||
import com.ruoyi.common.utils.aliyun.AliyunNlsUtils;
|
||||
import com.ruoyi.common.utils.http.HttpUtils;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
@Component
|
||||
public class SmsRequestClient {
|
||||
|
||||
private static final int LIMIT = 10; // 每秒允许10次请求
|
||||
private static final long REFRESH_PERIOD = 1000; // 1秒刷新
|
||||
private final AtomicInteger tokenBucket = new AtomicInteger(LIMIT);
|
||||
private final AtomicLong lastRefreshTime = new AtomicLong(System.currentTimeMillis());
|
||||
|
||||
/**
|
||||
* API密钥账号
|
||||
*/
|
||||
@Value("${sms.secretName}")
|
||||
private String secretName;
|
||||
/**
|
||||
* API密钥
|
||||
*/
|
||||
@Value("${sms.secretKey}")
|
||||
private String secretKey;
|
||||
/**
|
||||
* 短信模板ID
|
||||
*/
|
||||
@Value("${sms.templateId}")
|
||||
private String templateId;
|
||||
|
||||
/**
|
||||
* 发送短信
|
||||
* @param requestDTO
|
||||
* @return
|
||||
*/
|
||||
public AjaxResult sendSms(SmsRequestDTO requestDTO){
|
||||
|
||||
if (!tryAcquireToken()) {
|
||||
return AjaxResult.error("发送失败:当前发送人数过多,请稍后重试");
|
||||
}
|
||||
|
||||
//参数
|
||||
requestDTO.setSecretName(secretName);
|
||||
requestDTO.setSecretKey(secretKey);
|
||||
requestDTO.setTemplateId(templateId);
|
||||
|
||||
String msg="";
|
||||
try {
|
||||
String json= JSON.toJSONString(requestDTO);
|
||||
String result= HttpUtils.snedSmsPost(AliyunNlsUtils.getSmsUrl(),json);
|
||||
JSONObject responseJson = JSONObject.parseObject(result);
|
||||
System.out.println("调用返回===="+responseJson);
|
||||
msg = responseJson.getString("msg");
|
||||
System.out.println("返回消息"+msg);
|
||||
if (!"0".equals(responseJson.getString("code"))) {
|
||||
msg="发送失败:" + msg;
|
||||
return AjaxResult.error(msg);
|
||||
}else{
|
||||
msg="发送成功:" + msg;
|
||||
return AjaxResult.success(msg);
|
||||
}
|
||||
}catch (Exception e){
|
||||
return AjaxResult.error(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private boolean tryAcquireToken() {
|
||||
long now = System.currentTimeMillis();
|
||||
// 刷新令牌桶
|
||||
if (now - lastRefreshTime.get() >= REFRESH_PERIOD) {
|
||||
tokenBucket.set(LIMIT);
|
||||
lastRefreshTime.set(now);
|
||||
}
|
||||
// 尝试获取令牌
|
||||
return tokenBucket.decrementAndGet() >= 0;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user