redis开始事物,秒杀demo
1.main
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | 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(); } } |
今日事今日毕