zoukankan      html  css  js  c++  java
  • 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();
    	}
    
    }
    

      

    今日事今日毕
  • 相关阅读:
    留言板
    阿里云ECS 个人博客搭建流程
    安卓包 无崩溃文件的崩溃问题解决
    win10家庭版 远程桌面解决方案
    python int(a/b)和//的区别(转)
    git基本操作
    《代码整洁之道》读后总结
    《人月神话》的观点:是与非?
    小白第一次装机体验
    python2和python3之间的差异和区别
  • 原文地址:https://www.cnblogs.com/gjack/p/8848387.html
Copyright © 2011-2022 走看看