创建红包
Map<String, String> map = new HashMap<>();
for (int i = 0; i < 10; i++) {
map.put("id", "rid" + i);
map.put("money", i +"");
jedisClient.lpush("hongbaoPoolKey", JSONUtils.toJSONString(map));
}
lua脚本
local userId = ARGV[1]
if redis.call("SISMEMBER", KEYS[3], userId) ==1 then
return nil
else
local hongbao = redis.call("RPOP", KEYS[1]);
if hongbao then
local x = cjson.decode(hongbao);
x['userId'] = userId;
local re = cjson.encode(x);
redis.call("SADD", KEYS[3], userId)
redis.call("LPUSH", KEYS[2], re)
return re
else
return nil
end
end
实现抢红包
public class Qianghongbao {
private static JedisPool jedisPool = new JedisPool("192.168.27.128", 6379);
private static AtomicInteger atomicInteger = new AtomicInteger(0);
public static void main(String[] args) {
String script = "local userId = ARGV[1]\n" +
"if redis.call(\"SISMEMBER\", KEYS[3], userId) == 1 then\n" +
" return nil\n" +
"else\n" +
" local hongbao = redis.call(\"RPOP\", KEYS[1]);\n" +
" if hongbao then\n" +
" local x = cjson.decode(hongbao);\n" +
" x['userId'] = userId;\n" +
" local re = cjson.encode(x);\n" +
" redis.call(\"SADD\", KEYS[3], userId)\n" +
" redis.call(\"LPUSH\", KEYS[2], re)\n" +
" return re\n" +
" else\n" +
" return nil\n" +
" end\n" +
"end";
int n = 10;
// 实现一起开始抢
CyclicBarrier cyclicBarrier = new CyclicBarrier(n);
//抢完之后,统计多少人抢到了红包
CyclicBarrier cyclicBarrier2 = new CyclicBarrier(n, new Runnable() {
@Override
public void run() {
System.out.println("共" + atomicInteger.get() + "抢到了红包");
}
});
/* System.out.println( resource.eval(script, 3, "hongbaoPoolKey", "hongbaoDetails",
"userSetForGrabbed", "1234541"));*/
for (int i = 0; i < n; i++) {
if (i == 19) {
System.out.println();
}
new Thread(new Runnable() {
@Override
public void run() {
Jedis resource = null;
try {
cyclicBarrier.await();
// 每个线程需要获取一个连接
resource = jedisPool.getResource();
String userId = UUID.randomUUID().toString();
Object eval = resource.eval(script, 3, "hongbaoPoolKey", "hongbaoDetails",
"userSetForGrabbed", userId);
if (eval != null) {
atomicInteger.addAndGet(1);
System.out.println(userId + "抢到了红包");
} else {
System.out.println(userId + "没有抢到红包");
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (resource != null) {// 连接池最多有8个连接,用完记得关闭
resource.close();
}
try {
cyclicBarrier2.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
}