redis秒杀业务逻辑
package com.woniu.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;
@RestController
public class ProducterController {
@Autowired
private StringRedisTemplate srt;
@RequestMapping("order")
public void order() {
String mylock = null;
try {
mylock = "mylock";
Boolean result = srt.opsForValue().setIfAbsent(mylock, "lxy", 10, TimeUnit.SECONDS);
while (!result) {
try {
TimeUnit.MICROSECONDS.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
result = srt.opsForValue().setIfAbsent(mylock, "lxy", 10, TimeUnit.SECONDS);
}
String finalMylock = mylock;
Thread th = new Thread(() ->{
while (true) {
try {
TimeUnit.SECONDS.sleep(3);
srt.expire(finalMylock, 10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
th.setDaemon(true);
th.start();
String stock = srt.opsForValue().get("stock");
Integer realStock = Integer.valueOf(stock);
if (realStock > 0) {
realStock--;
System.out.println("下单成功,剩余库存量" + realStock);
srt.opsForValue().set("stock", realStock + "");
} else {
System.out.println("下单失败,没有库存了");
}
} finally {
srt.delete(mylock);
}
}
}