//对比防重删令牌 String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; Jedis jedis = jedisPool.getResource(); Long eval = (Long) jedis.eval(script, Collections.singletonList(KEYS[1]),Collections.singletonList(ARGV[1]));
"if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end" 判断lua脚本的 key KEYS[1,和 value ARGV[1],如果key 等于value ,马上删除,如果key不等于value,
说明没匹配(此key 和此 value 不是一对)上或者value不存在,返回 0 end,判断返回值 eval 是否为 0 即可
使用范例:
/** * 验证手机验证码 * * @param phone 手机号 * @param code 用户输入的验证码 * @return */ public boolean verifyPhoneCode(PhoneCodeEnum phoneCodeEnum, String phone, String code) { Long eval; Jedis jedis = null; try { jedis = this.getJedis(); // Redis 第一个库太拥挤,不方便查看,所以放第二个库中 jedis.select(phoneCodeEnum.getIndex()); String key = phoneCodeEnum.getCodeKey() + phone; String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; eval = (Long) jedis.eval(script, BrxUtils.asList(key), BrxUtils.asList(code)); } finally { this.close(jedis); } boolean isOk = eval != 0; if (!isOk) { log.error("phone:{},验证码:{}不合法", phone, code); } return isOk; }