|
@@ -0,0 +1,87 @@
|
|
|
+package com.llisoft.service.sms.service;
|
|
|
+
|
|
|
+import java.util.Objects;
|
|
|
+import java.util.concurrent.TimeUnit;
|
|
|
+
|
|
|
+import org.slf4j.Logger;
|
|
|
+import org.slf4j.LoggerFactory;
|
|
|
+import org.springframework.beans.factory.annotation.Autowired;
|
|
|
+import org.springframework.stereotype.Service;
|
|
|
+
|
|
|
+import com.llisoft.common.util.RandomUtil;
|
|
|
+import com.llisoft.service.sms.util.RedisUtil;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 短信服务
|
|
|
+ * @author YangJie [2019年4月25日]
|
|
|
+ */
|
|
|
+@Service
|
|
|
+public class SmsService {
|
|
|
+
|
|
|
+ private Logger logger = LoggerFactory.getLogger(SmsService.class);
|
|
|
+
|
|
|
+ @Autowired
|
|
|
+ private AliyunService aliyunService;
|
|
|
+
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 发送验证码
|
|
|
+ * 同手机号 每分钟1条/每小时5条/每天10条
|
|
|
+ * @param phone
|
|
|
+ */
|
|
|
+ public boolean sendCode(String phone) {
|
|
|
+ logger.info("发送验证码: {}", phone);
|
|
|
+ // 每分钟1条
|
|
|
+ String key = phone + "_limit_minute";
|
|
|
+ String result = RedisUtil.get(key);
|
|
|
+ if(Objects.nonNull(result)) {
|
|
|
+ logger.warn("每分钟限制1条: {}", phone);
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ RedisUtil.set(key, "", 1, TimeUnit.MINUTES);
|
|
|
+ // 每小时5条
|
|
|
+ key = phone + "_limit_hour";
|
|
|
+ result = RedisUtil.get(key);
|
|
|
+ if(Objects.nonNull(result)) {
|
|
|
+ int count = Integer.parseInt(result);
|
|
|
+ if(count >= 5) {
|
|
|
+ logger.warn("每小时限制5条: {}", phone);
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ RedisUtil.set(key, count, 1, TimeUnit.HOURS);
|
|
|
+ }else {
|
|
|
+ RedisUtil.set(key, 1, 1, TimeUnit.HOURS);
|
|
|
+ }
|
|
|
+ // 每天10条
|
|
|
+ key = phone + "_limit_day";
|
|
|
+ result = RedisUtil.get(key);
|
|
|
+ if(Objects.nonNull(result)) {
|
|
|
+ int count = Integer.parseInt(result);
|
|
|
+ if(count >= 10) {
|
|
|
+ logger.warn("每小时限制5条: {}", phone);
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ RedisUtil.set(key, count, 1, TimeUnit.DAYS);
|
|
|
+ }else {
|
|
|
+ RedisUtil.set(key, 1, 1, TimeUnit.DAYS);
|
|
|
+ }
|
|
|
+ // 发送短信
|
|
|
+ String code = String.valueOf(RandomUtil.getRandomInt(4));
|
|
|
+ RedisUtil.set(phone + "_" + code, "", 10, TimeUnit.MINUTES); // 有效期10分钟
|
|
|
+ aliyunService.sendCode(phone, code); // 第三方发送短信
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 检查验证码
|
|
|
+ * @param phone
|
|
|
+ * @param code
|
|
|
+ * @return
|
|
|
+ */
|
|
|
+ public boolean checkCode(String phone, String code) {
|
|
|
+ logger.info("检查验证码: {} : {}", phone, code);
|
|
|
+ String result = RedisUtil.get(phone + "_" + code);
|
|
|
+ return Objects.nonNull(result);
|
|
|
+ }
|
|
|
+
|
|
|
+}
|