目录
- 【前言】
- 【实现过程】
- 一、问题分析
- 二、解决方案
- 三、代码改造
- 【总结】
【前言】
cash loan(一):redis实现计数器防刷 中介绍了项目中应用redis来做计数器的实现过程,最近自己看了些关于redis实现分布式锁的代码后,发现在redis分布式锁中出现一个问题在这版计数器中同样会出现,于是融入了lua脚本进行升级改造有了redis+lua版本。
【实现过程】
一、问题分析
如果set命令设置上,但是在设置失效时间时由于网络抖动等原因导致没有设置成功,这时就会出现死计数器(类似死锁);
二、解决方案
redis+lua是一个很好的解决方案,使用脚本使得set命令和expire命令一同达到redis被执行且不会被干扰,在很大程度上保证了原子操作;
为什么说是很大程度上保证原子操作而不是完全保证?因为在redis内部执行的时候出问题也有可能出现问题不过概率非常小;即使针对小概率事件也有相应的解决方案,比如解决死锁一个思路值得参考:防止死锁会将锁的值存成一个时间戳,即使发生没有将失效时间设置上在判断是否上锁时可以加上看看其中值距现在是否超过一个设定的时间,如果超过则将其删除重新设置锁。
三、代码改造
1、redis+lua锁的实现
package han.zhang.utils;
import org.springframework.data.redis.core.stringredistemplate;
import org.springframework.data.redis.core.script.digestutils;
import org.springframework.data.redis.core.script.redisscript;
import java.util.collections;
import java.util.uuid;
public class redislock {
private static final logutils logger = logutils.getlogger(redislock.class);
private final stringredistemplate stringredistemplate;
private final string lockkey;
private final string lockvalue;
private boolean locked = false;
/**
* 使用脚本在redis服务器执行这个逻辑可以在一定程度上保证此操作的原子性
* (即不会发生客户端在执行setnx和expire命令之间,发生崩溃或失去与服务器的连接导致expire没有得到执行,发生永久死锁)
* <p>
* 除非脚本在redis服务器执行时redis服务器发生崩溃,不过此种情况锁也会失效
*/
private static final redisscript<boolean> setnx_and_expire_script;
static {
stringbuilder sb = new stringbuilder();
sb.append("if (redis.call('setnx', keys[1], argv[1]) == 1) then\n");
sb.append("\tredis.call('expire', keys[1], tonumber(argv[2]))\n");
sb.append("\treturn true\n");
sb.append("else\n");
sb.append("\treturn false\n");
sb.append("end");
setnx_and_expire_script = new redisscriptimpl<>(sb.tostring(), boolean.class);
}
private static final redisscript<boolean> del_if_get_equals;
sb.append("if (redis.call('get', keys[1]) == argv[1]) then\n");
sb.append("\tredis.call('del', keys[1])\n");
del_if_get_equals = new redisscriptimpl<>(sb.tostring(), boolean.class);
public redislock(stringredistemplate stringredistemplate, string lockkey) {
this.stringredistemplate = stringredistemplate;
this.lockkey = lockkey;
this.lockvalue = uuid.randomuuid().tostring() + "." + system.currenttimemillis();
private boolean dotrylock(int lockseconds) {
if (locked) {
throw new illegalstateexception("already locked!");
}
locked = stringredistemplate.execute(setnx_and_expire_script, collections.singletonlist(lockkey), lockvalue,
string.valueof(lockseconds));
return locked;
* 尝试获得锁,成功返回true,如果失败立即返回false
*
* @param lockseconds 加锁的时间(秒),超过这个时间后锁会自动释放
public boolean trylock(int lockseconds) {
try {
return dotrylock(lockseconds);
} catch (exception e) {
logger.error("trylock error", e);
return false;
* 轮询的方式去获得锁,成功返回true,超过轮询次数或异常返回false
* @param lockseconds 加锁的时间(秒),超过这个时间后锁会自动释放
* @param tryintervalmillis 轮询的时间间隔(毫秒)
* @param maxtrycount 最大的轮询次数
public boolean trylock(final int lockseconds, final long tryintervalmillis, final int maxtrycount) {
int trycount = 0;
while (true) {
if (++trycount >= maxtrycount) {
// 获取锁超时
return false;
}
try {
if (dotrylock(lockseconds)) {
return true;
}
} catch (exception e) {
logger.error("trylock error", e);
thread.sleep(tryintervalmillis);
} catch (interruptedexception e) {
logger.error("trylock interrupted", e);
* 解锁操作
public void unlock() {
if (!locked) {
throw new illegalstateexception("not locked yet!");
locked = false;
// 忽略结果
stringredistemplate.execute(del_if_get_equals, collections.singletonlist(lockkey), lockvalue);
private static class redisscriptimpl<t> implements redisscript<t> {
private final string script;
private final string sha1;
private final class<t> resulttype;
public redisscriptimpl(string script, class<t> resulttype) {
this.script = script;
this.sha1 = digestutils.sha1digestashex(script);
this.resulttype = resulttype;
@override
public string getsha1() {
return sha1;
public class<t> getresulttype() {
return resulttype;
public string getscriptasstring() {
return script;
}
2、借鉴锁实现redis+lua计数器
(1)工具类
package han.zhang.utils;
import org.springframework.data.redis.core.stringredistemplate;
import org.springframework.data.redis.core.script.digestutils;
import org.springframework.data.redis.core.script.redisscript;
import java.util.collections;
public class countutil {
private static final logutils logger = logutils.getlogger(countutil.class);
private final stringredistemplate stringredistemplate;
/**
* 使用脚本在redis服务器执行这个逻辑可以在一定程度上保证此操作的原子性
* (即不会发生客户端在执行setnx和expire命令之间,发生崩溃或失去与服务器的连接导致expire没有得到执行,发生永久死计数器)
* <p>
* 除非脚本在redis服务器执行时redis服务器发生崩溃,不过此种情况计数器也会失效
*/
private static final redisscript<boolean> set_and_expire_script;
static {
stringbuilder sb = new stringbuilder();
sb.append("local visittimes = redis.call('incr', keys[1])\n");
sb.append("if (visittimes == 1) then\n");
sb.append("\tredis.call('expire', keys[1], tonumber(argv[1]))\n");
sb.append("\treturn false\n");
sb.append("elseif(visittimes > tonumber(argv[2])) then\n");
sb.append("\treturn true\n");
sb.append("else\n");
sb.append("end");
set_and_expire_script = new redisscriptimpl<>(sb.tostring(), boolean.class);
}
public countutil(stringredistemplate stringredistemplate) {
this.stringredistemplate = stringredistemplate;
public boolean isovermaxvisittimes(string key, int seconds, int maxtimes) throws exception {
try {
return stringredistemplate.execute(set_and_expire_script, collections.singletonlist(key), string.valueof(seconds), string.valueof(maxtimes));
} catch (exception e) {
logger.error("redisbusiness>>>isovermaxvisittimes; get visit times exception; key:" + key + "result:" + e.getmessage());
throw new exception("already over maxvisittimes");
}
private static class redisscriptimpl<t> implements redisscript<t> {
private final string script;
private final string sha1;
private final class<t> resulttype;
public redisscriptimpl(string script, class<t> resulttype) {
this.script = script;
this.sha1 = digestutils.sha1digestashex(script);
this.resulttype = resulttype;
@override
public string getsha1() {
return sha1;
public class<t> getresulttype() {
return resulttype;
public string getscriptasstring() {
return script;
}
(2)调用测试代码
public void run(string... strings) {
countutil countutil = new countutil(springutils.getstringredistemplate());
try {
for (int i = 0; i < 10; i++) {
boolean overmax = countutil.isovermaxvisittimes("zhanghantest", 600, 2);
if (overmax) {
system.out.println("超过i:" + i + ":" + overmax);
} else {
system.out.println("没超过i:" + i + ":" + overmax);
}
}
} catch (exception e) {
logger.error("exception {}", e.getmessage());
}
}
(3)测试结果
【总结】
1、用心去不断的改造自己的程序;
2、用代码改变世界。
到此这篇关于redis+lua实现计数器接口防刷(升级版)的文章就介绍到这了,更多相关redis计数器内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!