短信验证码限流

2020-10-29  本文已影响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;
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读