1. 直接service,我们会介绍两种秒杀模式
public interface GoodsService { /** * 通过lua脚本实现的秒杀 * @param skuCode 商品编码 * @param buyNum 购买数量 * @return 购买数量 */ Long flashSellByLuaScript(String skuCode,int buyNum); /** * 通过redis 事务 实现的秒杀 * @param skuCode 商品编码 * @param buyNum 购买数量 * @return 购买数量 */ Long flashSellByRedisWatch(String skuCode,int buyNum);}
2. service实现类
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.StringRedisTemplate;import org.springframework.data.redis.core.ValueOperations;import org.springframework.data.redis.core.script.DefaultRedisScript;import org.springframework.data.redis.serializer.RedisSerializer;import org.springframework.stereotype.Service;import javax.annotation.Resource;import java.util.Collections;import java.util.List;@Servicepublic class GoodsServiceImpl implements GoodsService { @Resource private StringRedisTemplate stringRedisTemplate; @Override public Long flashSellByLuaScript(String skuCode,int num) { //下面是lua脚本 String luaScript ="local buyNum = ARGV[1]\n" + "local goodsKey = KEYS[1] \n" + "local goodsNum = redis.call('get',goodsKey) \n" + "if goodsNum >= buyNum \n" + "then redis.call('decrby',goodsKey,buyNum) \n" + "return buyNum \n" + "else \n" + "return '0'\n" + "end\n" + "\n" ; DefaultRedisScript
3. controller
但是首先要向你的redis里面仍一个数据,key='xiaomi',value='100'
@ApiOperation(value = "用事务秒杀测试接口", notes = "用事务秒杀测试接口")@RequestMapping(value = "/miaoTransaction", method = RequestMethod.GET)@ResponseBody public Long miaoTransaction() { Long res = goodsService.flashSellByRedisWatch("xiaomi", 1); return res; } @ApiOperation(value = " 秒杀Lua测试接口", notes = "秒杀Lua测试接口") @RequestMapping(value = "/miaoLua", method = RequestMethod.GET) @ResponseBody public Long miaoLua() { Long res = goodsService.flashSellByRedisWatch("xiaomi", 1); System.out.println(res.toString()); return res; }