|
@@ -1,12 +1,20 @@
|
|
|
package com.sf.service;
|
|
|
|
|
|
import com.sf.utils.RedisUtils;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
|
+import org.springframework.core.io.ClassPathResource;
|
|
|
import org.springframework.dao.DataAccessException;
|
|
|
import org.springframework.data.redis.core.RedisOperations;
|
|
|
import org.springframework.data.redis.core.SessionCallback;
|
|
|
+import org.springframework.data.redis.core.script.DefaultRedisScript;
|
|
|
+import org.springframework.scripting.support.ResourceScriptSource;
|
|
|
import org.springframework.stereotype.Service;
|
|
|
|
|
|
+import java.util.ArrayList;
|
|
|
+import java.util.List;
|
|
|
+
|
|
|
+@Slf4j
|
|
|
@Service
|
|
|
public class RedisServiceImpl implements RedisService {
|
|
|
|
|
@@ -15,6 +23,9 @@ public class RedisServiceImpl implements RedisService {
|
|
|
|
|
|
@Override
|
|
|
public void seckill(String userId, String goodsId) {
|
|
|
+ // 先判断 是否在秒杀有效时间内
|
|
|
+ // 也就是当前时间 是否 >= startTime <= endTime
|
|
|
+
|
|
|
// goodsId = 1
|
|
|
// 1_stock_num
|
|
|
// String key = goodsId + "_stock_num";
|
|
@@ -25,7 +36,8 @@ public class RedisServiceImpl implements RedisService {
|
|
|
// Long decr = redisUtils.decr(key);
|
|
|
// System.out.println(decr);
|
|
|
// }
|
|
|
- handleByTran(userId, goodsId);
|
|
|
+// handleByTran(userId, goodsId);
|
|
|
+ handleByLua(userId, goodsId);
|
|
|
|
|
|
// 加锁 乐观锁和悲观锁
|
|
|
// 以悲观的态度看待 如果修改数据时不增加锁 一定会出现问题
|
|
@@ -69,11 +81,28 @@ public class RedisServiceImpl implements RedisService {
|
|
|
operations.multi();
|
|
|
redisUtils.decr(key);
|
|
|
// 代表一笔订单生成 订单id=商品id+用户id
|
|
|
- redisUtils.set(goodsId + "_" + userId, "1");
|
|
|
+ redisUtils.set("order::" + goodsId + "_" + userId, "1");
|
|
|
return operations.exec();
|
|
|
}
|
|
|
};
|
|
|
- redisUtils.execute(sessionCallback);
|
|
|
+ Object object = redisUtils.execute(sessionCallback);
|
|
|
+ System.out.println(object);
|
|
|
+ }
|
|
|
+
|
|
|
+ public void handleByLua(String userId, String goodsId) {
|
|
|
+ DefaultRedisScript<Long> script = new DefaultRedisScript<>();
|
|
|
+ script.setResultType(Long.class);
|
|
|
+
|
|
|
+ ClassPathResource classPathResource = new ClassPathResource("script/seckill.lua");
|
|
|
+ ResourceScriptSource resourceScriptSource = new ResourceScriptSource(classPathResource);
|
|
|
+ script.setScriptSource(resourceScriptSource);
|
|
|
+
|
|
|
+ List<String> keyList = new ArrayList<>();
|
|
|
+ keyList.add(userId);
|
|
|
+ keyList.add(goodsId);
|
|
|
+
|
|
|
+ Object result = redisUtils.execute(script, keyList);
|
|
|
+ log.info("userId:{},goodsId:{},result:{}", userId, goodsId, result);
|
|
|
}
|
|
|
|
|
|
@Override
|
|
@@ -95,5 +124,9 @@ public class RedisServiceImpl implements RedisService {
|
|
|
// map.put("2", 10L);
|
|
|
// redisUtils.setAllMap("stock_num", map);
|
|
|
|
|
|
+
|
|
|
+ // <1_startTime,"20220224">
|
|
|
+ // <1_endTime,"20220227">
|
|
|
+
|
|
|
}
|
|
|
}
|