redis开始事物,秒杀demo

1.main

package redis;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import redis.clients.jedis.Jedis;

public class test1 {
	public static void main(String[] args) {
		Jedis jedis = new Jedis("127.0.0.1");	
		jedis.set("iphoneX", "1000");	
		jedis.close();
		ExecutorService executor = Executors.newFixedThreadPool(1050);
		
		for(int i=0;i<20000;i++){
			executor.execute(new threadtest("user"+i));
		}
		executor.shutdown();		
	}
}

2.newRunnable

package redis;

import java.util.List;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

public class threadtest implements Runnable {
	String productKey="iphoneX";
	String user;
	Jedis jedis = new Jedis("127.0.0.1");
	
	public threadtest(String user) {
		this.user=user;
	}

	public void run() {
		
		jedis.watch("iphoneX");
		String number = jedis.get("iphoneX");
		int num = Integer.valueOf(number);
		if(num >0 &&num<=1000){
			Transaction tx = jedis.multi();
			tx.incrBy(productKey,-1);
			List<Object> list = tx.exec();
			if(list==null || list.size()==0){
				System.out.println(user+"抢购失败");
            }else{
            	for(Object success :list){
            		System.out.println(user+"---("+success+")抢购成功");		 
            	}
            }
			
		}else{
			System.out.println(user+"被抢空了");
		}
		jedis.close();
	}

}

  

posted @ 2018-04-15 17:31  爱吃醋的工程师  阅读(126)  评论(0编辑  收藏  举报