redis+消息队列整合商品秒杀

描述主要思路


    @Autowired
    private StringRedisService redisService;
    @Autowired
    @Qualifier(value = "mapCache")
    private Map localOverMap;

    @ApiOperation(value = "秒杀", position = 3)
    @RequestMapping(value = "seckill", method = RequestMethod.GET)
    public SzResult seckill(
            @ApiParam(value = "productId ") @RequestParam(value = "productId", required = false) Long productId,
            HttpServletRequest request) {
        //内存标记,减少redis访问
        Boolean over = localOverMap.get(productId);
        if (Objects.isNull(over)) {
            System.out.println("没有该商品");
            return new SzResult().error("没有该商品!");
        }
        if (over) {
            System.out.println("已经被抢空");
            return new SzResult().error("已经被抢空!");
        }
        Long decr = redisService.decr("Seckill_" + productId);
        if (decr.longValue() < 0) {
            localOverMap.put(productId, true);
            System.out.println("已经被抢空");
            return new SzResult().error("已经被抢空!");
        }
        //判断是否已经秒杀到了
        {
            //此处 主要用用户token,再查 秒杀订单,看看用户是否秒杀到了,
            // 如果秒杀到了,直接返回 不能重复秒杀
        }

        //入队
        {
            //此处使用消息队列让别的服务创建秒杀订单
        }
        System.out.println(decr);
        return new SzResult().success("秒杀成功!" + decr);
    }

    @ApiOperation(value = "初始化秒杀库存量", position = 3)
    @RequestMapping(value = "initSeckill", method = RequestMethod.GET)
    public SzResult seckill(
            @ApiParam(value = "productId ") @RequestParam(value = "productId", required = false) Long productId,
            @ApiParam(value = "count") @RequestParam(value = "count", required = false) Long count,
            HttpServletRequest request) {
        redisService.set("Seckill_" + productId, count + "", 60, TimeUnit.SECONDS);
        localOverMap.put(productId, false);
        return new SzResult().success("ok");
    }

自定义缓存

@Component
public class OtherConfig {

    /**
     * 自定义缓存
     *
     * @return
     */
    @Bean
    public Map mapCache() {
        return Maps.newLinkedHashMap();
    }
}

 

你可能感兴趣的:(redis+消息队列整合商品秒杀)