来源:https://www.jianshu.com/p/93cd65d07b56
public class RedisTest1Sub {
private static String key = “macbook”;
private static String num = "100";
private static ExecutorService executorService = Executors.newFixedThreadPool(8);
public static void main(String[] args) {
try{
for (int i = 1; i <= 600; i++) {
executorService.submit(new RedisTest1(“顾客”+i,key));
}
}finally {
executorService.shutdown();
}
}
}
public class RedisTest1 implements Runnable {
private Jedis jedis = new Jedis(“localhost”, 6379);
private String customerName;
private String key;
public RedisTest1(String customerName, String key) {
this.customerName = customerName;
this.key = key;
}
@Override
public void run() {
boolean success = false;
String data;
int currentNum;
while (!success) {//可重复抢购直到成功
//通过watch实现redis的incr(原子递增操作)
jedis.watch(key);
data = jedis.get(key);
currentNum = Integer.parseInt(data);
if (currentNum > 0) {
//开启事务
Transaction transaction = jedis.multi();
//设置新值,如果key的值被其它连接的客户端修改,那么当前连接的exec命令将执行失败
currentNum--;
transaction.set(key, String.valueOf(currentNum));
List res = transaction.exec();
if (res==null || res.size() == 0) {
System.out.println(res);
System.out.println(customerName + " 抢购失败");
success = false;
} else {
System.out.println(res);
success = true;
System.out.println(customerName + " 抢购成功,[" + key + "]剩余:" + currentNum);
}
} else {
System.out.println("商品售空,活动结束!");
System.exit(0);
}
}
}
}
在生产环境直接使用
public class RedisTes {
@Autowired
StringRedisTemplate stringRedisTemplate;
//实现秒杀
public void miaosha(){
String key = "goods";
String data ="";
int currentNum ;
//进行watch监听
stringRedisTemplate.watch(key);
data = stringRedisTemplate.opsForValue().get(key);
currentNum = Integer.parseInt(data);
if(currentNum>0){
//事务
stringRedisTemplate.setEnableTransactionSupport(true);
stringRedisTemplate.multi();
currentNum--;
stringRedisTemplate.opsForValue().set(key,String.valueOf(currentNum));
List<Object> exec = stringRedisTemplate.exec();
if(exec==null || exec.size()==0){
System.out.println(Thread.currentThread().getName()+"抢购失败");
}else {
System.out.println(Thread.currentThread().getName()+"抢购成功");
}
}else{
System.out.println(Thread.currentThread().getName()+"商品售罄");
}
}
}