package domain;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 秒杀
*/
public class SecKill {
public static String KEY = "kill";
public static void main(String args[]) {
ExecutorService service = Executors.newFixedThreadPool(20);
Jedis jedis = new Jedis("192.168.0.21", 6379, 1000);
jedis.set(SecKill.KEY, "100");
jedis.close();
for (int i = 0; i < 10000; i++) {
service.execute(new MyRunnable("secKill:"+i));
}
service.shutdown();
}
}
class MyRunnable implements Runnable {
private String userName;
private Jedis jedis = new Jedis("192.168.0.21", 6379, 1000);
public MyRunnable(String userName) {
this.userName = userName;
}
@Override
public void run() {
//创建监听
jedis.watch(SecKill.KEY);
//对物品数量检测
String num = jedis.get(SecKill.KEY);
if (Integer.parseInt(num) > 0) {
//获取事务
Transaction tx = jedis.multi();
//执行逻辑
tx.incrBy(SecKill.KEY, -1);
//提交事务
List<Object> result = tx.exec();
//执行事后逻辑
if (null == result) {
//System.out.println("抢购失败,物品剩余资源不足,用户id:" + userName);
jedis.close();
return;
}
if (result.size() == 0) {
//System.out.println("抢购失败,物品剩余" + num + ",用户id:" + userName);
jedis.close();
return;
}
if (result.size() > 0) {
System.out.println("抢购成功,物品剩余" + result.get(0) + ",用户id:" + userName);
}
}
//关闭资源
jedis.close();
}
}
redis使用事物
猜你喜欢
转载自blog.csdn.net/bb23417274/article/details/83185022
今日推荐
周排行