美文网首页
短信验证码限流

短信验证码限流

作者: 刘彦青 | 来源:发表于2020-10-29 19:42 被阅读0次
public class SmsSendHandler implements SmsPreSendHandler, SmsValidator {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public SmsSendHandler() {
    }

    @Override
    public void process(String mobile, String code, String scene, SmsProperties properties) {

        AliyunSmsProperties aliyunSmsProperties = (AliyunSmsProperties) properties;

        AliyunSmsProperties.SignTemplate signTemplate = (AliyunSmsProperties.SignTemplate) aliyunSmsProperties.getConfigs().get(scene);
        boolean check = this.stringRedisTemplate.opsForValue().setIfAbsent("sms:" + mobile + ":lock", "lock");
        if (!check) {
            String errMsg = "触发[" + ((AliyunSmsProperties.SignTemplate) aliyunSmsProperties.getConfigs().get(scene)).getTimeout() + "s]流控";
            log.error(errMsg);
            throw new IllegalArgumentException(errMsg);
        } else {
            this.stringRedisTemplate.expire("sms:" + mobile + ":lock", (long) ((AliyunSmsProperties.SignTemplate) aliyunSmsProperties.getConfigs().get(scene)).getTimeout(), TimeUnit.SECONDS);
            this.stringRedisTemplate.opsForValue().set("sms:" + mobile + ":" + scene + ":code", code, (long) signTemplate.getExpire(), TimeUnit.SECONDS);
        }
    }

    @Override
    public boolean valid(String mobile, String code, String scene) {
        String cache = (String) this.stringRedisTemplate.opsForValue().get("sms:" + mobile + ":" + scene + ":code");
        boolean result = Objects.equals(code, cache);
        if (result && code != null) {
            this.stringRedisTemplate.delete("sms:" + mobile + ":" + scene + ":code");
            return result;
        } else {
            return false;
        }
    }
}

相关文章

网友评论

      本文标题:短信验证码限流

      本文链接:https://www.haomeiwen.com/subject/xvslvktx.html