思路:通过redis控制库存,先减1,如果库存小于0再加1。
代码:
@Override
public ServiceResult testA() {
jedisClient.setString("TEST:AAA", "100");
jedisClient.setString("TEST:BBB", "0");
for (int i = 0; i < 1000; ++i) {
asyncService.test();
}
Object o = null;
return ServiceResult.success(o);
}
@Async
@Override
public void test() {
int i = 0;
boolean minus = false;
boolean ineedAdd = false;
boolean add = false;
try{
Long l = jedisClient.decrement("TEST:AAA");
minus = true;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
LOGGER.info("has:{}", l);
if (l<0){
LOGGER.info("has no");
ineedAdd = true;
jedisClient.increment("TEST:AAA");
add = true;
}
}catch (Exception e){
LOGGER.error("error:{}", e.getMessage());
//此处为异常处理,如redis链接数不够用,等待超时
if (minus && ineedAdd && !add){
boolean iTry = true;
int num = 0;
while (iTry && num < 10){
try {
jedisClient.increment("TEST:AAA");
iTry = false;
}catch (Exception e1){
LOGGER.error("try error:{}", e1.getMessage());
num ++;
}
}
}
}
}