码迷,mamicode.com
首页 > 其他好文 > 详细

关于使用 lua 脚本抢红包

时间:2016-09-01 18:02:56      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

1 java代码

package com.robert.RedisTest;

import redis.clients.jedis.Jedis;

public class RedisClient {
    
    public static void main(String[] args) {
        System.out.println(getHongBao());
        System.out.println();
    }
    
    public static void doAppend(StringBuilder script,String expression){
        script.append(expression+"\n");
    }
    
    public static int getHongBao(){
        Jedis jedis = new Jedis("localhost", 6379);
        jedis.set("name","robert");
        StringBuilder script = new StringBuilder();
        doAppend(script,"local result = 0");
        doAppend(script,"local afterDescNum = redis.call(‘decr‘, KEYS[1])");
        doAppend(script,"if afterDescNum>=0 then");
        doAppend(script,"result=1");
        doAppend(script,"else ");
        doAppend(script,"result=0");
        doAppend(script,"redis.call(‘set‘, KEYS[1], 0)");
        doAppend(script,"end");
        script.append("return result");
        Object result = jedis.eval(script.toString(),1,"hongbaoNum");
        int flag = Integer.parseInt(String.valueOf(result));
        System.out.println(Thread.currentThread().getName()+" : "+flag);
        return flag;
    }
}

qianghongbao.lua

local result = 0
local afterDescNum = redis.call(‘decr‘, KEYS[1])
if afterDescNum>=0 then
result=1
else 
result=0
redis.call(‘set‘, KEYS[1], 0)
end
return result

 

关于使用 lua 脚本抢红包

标签:

原文地址:http://www.cnblogs.com/mengjianzhou/p/5830306.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!