Redis使用lua脚本实现increase + expire 的原子操作
2018-01-11 14:20
816 查看
lua脚本:
local current = redis.call('incrBy',KEYS[1],ARGV[1]);" +
" if current == tonumber(ARGV[1]) then" +
" local t = redis.call('ttl',KEYS[1]);" +
" if t == -1 then " +
" redis.call('expire',KEYS[1],ARGV[2])" +
" end;" +
" end;" +
" return current";
JedisCluter
public Long incrBy(final String key, final long step, final int defaultExpire) {
return new JedisClusterCommand<Long>(connectionHandler, maxRedirections, Protocol.Command.INCR) {
@Override
public Long execute(Jedis connection) {
if (defaultExpire > 0) {
Object val = connection.eval(ScriptConstant.INCRBY_1_EXPIRE, 1, new String[]{key, String.valueOf(step), String.valueOf(defaultExpire)});
return Long.valueOf(val.toString());
} else {
return connection.incrBy(key, step);
}
}
}.run(key);
}
local current = redis.call('incrBy',KEYS[1],ARGV[1]);" +
" if current == tonumber(ARGV[1]) then" +
" local t = redis.call('ttl',KEYS[1]);" +
" if t == -1 then " +
" redis.call('expire',KEYS[1],ARGV[2])" +
" end;" +
" end;" +
" return current";
JedisCluter
public Long incrBy(final String key, final long step, final int defaultExpire) {
return new JedisClusterCommand<Long>(connectionHandler, maxRedirections, Protocol.Command.INCR) {
@Override
public Long execute(Jedis connection) {
if (defaultExpire > 0) {
Object val = connection.eval(ScriptConstant.INCRBY_1_EXPIRE, 1, new String[]{key, String.valueOf(step), String.valueOf(defaultExpire)});
return Long.valueOf(val.toString());
} else {
return connection.incrBy(key, step);
}
}
}.run(key);
}
相关文章推荐
- 使用lua脚本和jedis实现redis的hmsetnx命令,操作hash表时不覆盖原有数据
- Redis之使用lua脚本操作redis数据库的原因
- redis哨兵模式使用lua脚本实现分布式锁
- redis实现附近的人,但jedis中没有相关api,那么直接使用lua脚本执行。
- Cocos2d-x使用Luajit将Lua脚本编译为bytecode,从而实现加密
- 使用Redis的脚本功能实现Redis中数据简单查询
- 使用ThinkPHP扩展,实现Redis的CURD操作。
- arm架构的独占读写指令ldrex和strex的使用详解(原子操作和自旋锁实现的基本原理)
- 【COCOS2DX-LUA 脚本开发之十】使用Lua CJSON库进行encode与decode操作完成对Json数据转化
- 【COCOS2DX-LUA 脚本开发之十】使用Lua CJSON库进行encode与decode操作完成对Json数据转化
- Cocos2d-x使用Luajit将Lua脚本编译为bytecode,从而实现加密
- 使用Boost的共享锁、条件变量、原子操作实现写优先的读写锁
- 使用vs2005 C语言调用lua脚本实现hello,world
- redis中使用java脚本实现分布式锁
- cocos2dx 使用Luajit将Lua脚本编译为bytecode,从而实现加密
- 【COCOS2DX-LUA 脚本开发之十】使用Lua CJSON库进行encode与decode操作完成对Json数据转化
- Cocos2d-x使用Luajit将Lua脚本编译为bytecode,从而实现加密
- android使用lua脚本实现动态逻辑
- unp2 02 使用信号量实现的原子操作
- Php+Redis 实现Redis提供的lua脚本功能