|
@@ -2,6 +2,9 @@ package com.sf.service;
|
|
|
|
|
|
import com.sf.utils.RedisUtils;
|
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
|
+import org.springframework.dao.DataAccessException;
|
|
|
+import org.springframework.data.redis.core.RedisOperations;
|
|
|
+import org.springframework.data.redis.core.SessionCallback;
|
|
|
import org.springframework.stereotype.Service;
|
|
|
|
|
|
@Service
|
|
@@ -14,14 +17,64 @@ public class RedisServiceImpl implements RedisService {
|
|
|
public void seckill(String userId, String goodsId) {
|
|
|
|
|
|
|
|
|
- String key = goodsId + "_stock_num";
|
|
|
- Integer num = (Integer) redisUtils.get(key);
|
|
|
- if (num > 0) {
|
|
|
- Long decr = redisUtils.decr(key);
|
|
|
- System.out.println(decr);
|
|
|
- }
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+ handleByTran(userId, goodsId);
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
}
|
|
|
|
|
|
+
|
|
|
+ public void handleByTran(String userId, String goodsId) {
|
|
|
+
|
|
|
+ SessionCallback sessionCallback = new SessionCallback() {
|
|
|
+ @Override
|
|
|
+ public Object execute(RedisOperations operations) throws DataAccessException {
|
|
|
+
|
|
|
+ String key = goodsId + "_stock_num";
|
|
|
+ operations.watch(key);
|
|
|
+ Integer num = (Integer) redisUtils.get(key);
|
|
|
+ if (num <= 0) {
|
|
|
+
|
|
|
+ return "已经被秒杀一空";
|
|
|
+ }
|
|
|
+ operations.multi();
|
|
|
+ redisUtils.decr(key);
|
|
|
+
|
|
|
+ redisUtils.set(goodsId + "_" + userId, "1");
|
|
|
+ return operations.exec();
|
|
|
+ }
|
|
|
+ };
|
|
|
+ redisUtils.execute(sessionCallback);
|
|
|
+ }
|
|
|
|
|
|
@Override
|
|
|
public void init() {
|