栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

redis + lua + rabbitmq实现高并发秒杀

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

redis + lua + rabbitmq实现高并发秒杀

mySeckill.lua

Lua优点:
减少网络开销:这个脚本只要执行一次,能减少网络传输
原子性:Redis将这个脚本作为原子执行要么全部成功或者失败,不担心并发问题,不需要事务,(PS:LUA脚本保证原子性,执行lua脚本时不会同时执行其它脚本或redis命令, 这种语义类似于MULTI/EXEC,这个lua脚本要么执行成功,要么执行失败)
复用性:lua一旦执行就能永久性保存Redis的数据,可以供其它客户端使用 

-- 全局函数: 求阶乘 function factorial(n) if n == 1 then return 1 else return n * fact(n - 1) end end
--商品库存Key
local product_stock_key = KEYS[1]
--商品购买用户记录Key
local buyersKey = KEYS[2]
--用户ID
local uid = KEYS[3]

--校验用户是否重复秒杀
local result = redis.call("sadd" , buyersKey , uid )
if(tonumber(result) == 1)
then
    --初次秒杀
    local stock = redis.call("lpop" , product_stock_key )
    
    if(stock)
    then
        --库存>0
        return 1
    else
        --库存不足
        return -1
    end
else
    --重复秒杀
    return 2
end

SeckillController 

 PS:@MyAcessLimter(count = 1000,timeout = 1)

redis + lua限流 + AOP实现接口对客户端限流_Zxdwr520的博客-CSDN博客

@RestController
@RequestMapping("/seckill")
@Slf4j
public class SeckillController {
    @Autowired
    private ProductService productService;
    @Resource
    private RedisTemplate redisTemplate;
    
    @Autowired
    OrderProducer orderProducer;

    
    @RequestMapping(value = "seckillProduct")
    @ResponseBody
    @MyAcessLimter(count = 1000,timeout = 1)
    public String seckillProduct(@RequestParam("uid") long userId, @RequestParam("pid") long productId){
        List list = Lists.newArrayList("product_stock_key_" + productId, "product_buyers_" + productId, userId + "");
        Long code = redisTemplate.execute(defaultRedisScript, list, "");
        if (code == -1) {
            return "库存不足";
        } else if (code == 2) {
            return "不允许重复秒杀";
        } else if (code == 1) {//加入队列
            return orderProducer.createOrderProducer("fanoutQueueOrder",productId,userId);
        }
        return "error";
    }


    
    @RequestMapping(value = "queryAll")
    @ResponseBody
    @MyAcessLimter(count = 1000,timeout = 1)//接口限流,每秒仅支持1000次请求
    public List queryAll(@RequestParam("seckillDate") String seckillDate) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        Gson gson = new Gson();
        List productList = productService.queryAll();//可以加条件查询
        if (productList == null){
            return null;
        }
        for (Product product: productList) {
            long productId = product.getId();
            redisTemplate.opsForValue().set("product_" + productId, gson.toJson(product));
            
            // 商品购买用户Set
            redisTemplate.opsForSet().add("product_buyers_" + product.getId(), "");
            for (int i = 0; i < product.getStock(); i++) {
                redisTemplate.opsForList().leftPush("product_stock_key_" + product.getId(), String.valueOf(i));
            }
            System.out.println(gson.toJson(product));
        }
        redisTemplate.opsForValue().set("seckill_plan_" + seckillDate, gson.toJson(productList));//把商品信息存入缓存

        return productList;
    }

 加入队列

@Component
@Slf4j
public class OrderProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisClient redisClient;

    @Autowired
    private DefaultRedisScript defaultRedisScript;

    public String createOrderProducer(String queueName,long productId,long userId){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("timestamp", System.currentTimeMillis());
        String messageId = String.valueOf(UUID.randomUUID());
        if (productId > 0 && userId > 0) {
            String productJson = (String) redisTemplate.opsForValue().get("product_" + productId);
            jsonObject.put("productJson", productJson);
            jsonObject.put("id", messageId);
            jsonObject.put("productId", productId + "");
            jsonObject.put("userId", userId + "");
            String jsonString = jsonObject.toJSONString();
            Message message = MessageBuilder.withBody(jsonString.getBytes())
                    .setDeliveryMode(MessageDeliveryMode.PERSISTENT)
                    .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                    .setDeliveryTag(System.currentTimeMillis())
                    .setContentEncoding("utf-8")
                    .setMessageId(messageId)
                    .build();
            rabbitTemplate.convertAndSend(queueName, message);
            return "success";
        }else {
            return "error";
        }
    }
}

 同步数据到DB

@Slf4j
@Component
public class OrderConsumer {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisClient redisClient;

    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductService productService;

    @RabbitListener(queues = "fanoutQueueOrder")
    public void createOrderConsumer(Message message, Channel channel) throws Exception {
        log.info("OrderConsumer  消费者收到消息:{}" , JSONObject.toJSONString(message));
        String messageId = message.getMessageProperties().getMessageId();
        String msg = new String(message.getBody(), "UTF-8");
        String messageIdRedis = //(String) redisTemplate.opsForValue().get("messageId");
                redisClient.getString("messageId");
        if (messageId != null) {//避免消费者消息重复
            if (!messageId.equals(messageIdRedis)) {
                redisClient.setString(messageId,messageId,3_000L * 600);// 写入缓存
                System.out.println("number==" + channel.getChannelNumber());
                JSONObject jsonObject = JSONObject.parseObject(msg);
                long deliverTag = message.getMessageProperties().getDeliveryTag();
                try {
                    //具体业务
                    String id = (String) jsonObject.get("id");
                    String productId = (String) jsonObject.get("productId");
                    String userId = (String) jsonObject.get("userId");
                    String productJson = (String) jsonObject.get("productJson");
                    if (productJson != null) {
                        Gson gson = new Gson();
                        Product product = gson.fromJson(productJson, Product.class);
                        Order order = new Order();
                        order.setProductId(Long.parseLong(productId));
                        order.setUserId(Long.parseLong(userId));
                        order.setId(id);
                        order.setOrderName("抢购" + product.getName());
                        order.setProductName(product.getName());
                        int p = productService.updateProduct(product.getId());//开启事务
                        if (p > 0) {
                            int i = orderService.insert(order);//开启事务
                            //loggerService.saveLog(jsonObject);//日志记录
                            if (i > 0 && p > 0) {
                                log.info("创建订单成功:i=" + i);
                                log.info("商品库存减-1成功:p=" + p);
                                LocalDateTime localDateTime = LocalDateTime.now();
                                Date dataTime = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
                                log.info("dataTime=" + dataTime);
                                channel.basicAck(deliverTag, true);//手动设置ack,消费成功,确认消息
                            }else {
                                channel.basicNack(deliverTag, false, true);
                            }
                        }
                    }

                }catch (Exception e){
                    try {
                        
                        channel.basicNack(deliverTag, false, true);
                    } catch (Exception ioException) {
                        log.error("重新放入队列失败,失败原因:{}",e.getMessage(),e);
                    }
                    log.error("TopicConsumer消费者出错,mq参数:{},错误信息:{}",message,e.getMessage(),e);

                    
                }
                //redisTemplate.opsForValue().set(messageId, messageId, 30, TimeUnit.SECONDS);//时间具体根据业务定

                System.out.println("消费消息jsonObject:" + jsonObject + ",messageId:" + messageId);
            }
        }

    }
}

 效果图:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/873794.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号