<三>rabbitmq秒杀项目基础

环境搭建

  1. 导入工程
  2. 订单服务启动
  3. 访问地址:http://localhost:9001/seckill-index.html
  4. 业务流程演示

启动Jemter

添加线程组
image.png

image.png
设置线程数
image.png
设置csv数据
image.png
http请求
image.png
响应断言
image.png
汇总报告
image.png

生产者代码的拆分

image.png

RabbitConfig

package com.boxuegu.seckillorder.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitConfig {

    /**
     * 声明交换机
     */
    @Bean
    public TopicExchange topicExchange() {
        return new TopicExchange("seckillOrder_topic_exchange", true, false);
    }


    /**
     * 声明队列
     */
    @Bean
    public Queue seckillOrder_queue() {
        return new Queue("seckillOrder_queue", true, false, false, null);
    }


    /**
     * 绑定
     */
    @Bean
    public Binding binding_queue() {
        return BindingBuilder.bind(this.seckillOrder_queue()).to(this.topicExchange()).with("seckillOrder.#.submitOrder");
    }
}

RedisConfig

package com.boxuegu.seckillorder.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean("redisTemplateStockCount")
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        //定义key序列化方式
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();//Long类型会出现异常信息;需要我们上面的自定义key生成策略,一般没必要
        //定义value的序列化方式
        template.setKeySerializer(redisSerializer);
        template.setValueSerializer(redisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

RedisLock

package com.boxuegu.seckillorder.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * redis 分布式锁
 */
@Component
public class RedisLock {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 加锁
     *
     * @param key   productId - 商品的唯一标志
     * @param value 当前时间+超时时间 也就是时间戳
     * @return
     */
    public boolean lock(String key, String value) {
        if (redisTemplate.opsForValue().setIfAbsent(key, value)) {//对应setnx命令
            //可以成功设置,也就是key不存在
            return true;
        }

        //判断锁超时 - 防止原来的操作异常,没有运行解锁操作  防止死锁
        String currentValue = (String) redisTemplate.opsForValue().get(key);
        //如果锁过期
        if (!StringUtils.isEmpty(currentValue) && Long.parseLong(currentValue) < System.currentTimeMillis()) {//currentValue不为空且小于当前时间
            //获取上一个锁的时间value
            String oldValue = (String) redisTemplate.opsForValue().getAndSet(key, value);//对应getset,如果key存在

            //假设两个线程同时进来这里,因为key被占用了,而且锁过期了。获取的值currentValue=A(get取的旧的值肯定是一样的),两个线程的value都是B,key都是K.锁时间已经过期了。
            //而这里面的getAndSet一次只会一个执行,也就是一个执行之后,上一个的value已经变成了B。只有一个线程获取的上一个值会是A,另一个线程拿到的值是B。
            if (!StringUtils.isEmpty(oldValue) && oldValue.equals(currentValue)) {
                //oldValue不为空且oldValue等于currentValue,也就是校验是不是上个对应的商品时间戳,也是防止并发
                return true;
            }
        }
        return false;
    }


    /**
     * 解锁
     *
     * @param key
     * @param value
     */
    public void unlock(String key, String value) {
        try {
            String currentValue = (String) redisTemplate.opsForValue().get(key);
            if (!StringUtils.isEmpty(currentValue) && currentValue.equals(value)) {
                redisTemplate.opsForValue().getOperations().delete(key);//删除key
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

SeckillGoodsService

package com.boxuegu.seckillorder.service;

import com.boxuegu.seckillorder.entity.PageResult;
import com.boxuegu.seckillorder.mapper.TbSeckillGoodsMapper;
import com.boxuegu.seckillorder.pojo.TbSeckillGoods;
import com.boxuegu.seckillorder.pojo.TbSeckillGoodsExample;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SeckillGoodsService {
    @Autowired
    private TbSeckillGoodsMapper seckillGoodsMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisTemplate redisTemplateStockCount;

    public List<TbSeckillGoods> findList() {
        //1. 从缓存中获取数据
        List<TbSeckillGoods> seckillGoodsList = redisTemplate.boundHashOps("seckillGoods").values();
        if (seckillGoodsList == null || seckillGoodsList.size() == 0) {
            TbSeckillGoodsExample example = new TbSeckillGoodsExample();
            TbSeckillGoodsExample.Criteria criteria = example.createCriteria();
            criteria.andStatusEqualTo("1");// 审核通过的商品
            criteria.andStockCountGreaterThan(0);//库存数大于0
            criteria.andStartTimeLessThanOrEqualTo(new Date());//开始日期小于等于当前日期
            criteria.andEndTimeGreaterThanOrEqualTo(new Date());//截止日期大于等于当前日期
            seckillGoodsList = seckillGoodsMapper.selectByExample(example);
            //2. 将列表数据装入缓存
            for (TbSeckillGoods seckillGoods : seckillGoodsList) {
                // 2.1 将商品放入redis缓存中
                redisTemplate.boundHashOps("seckillGoods").put(seckillGoods.getId(), seckillGoods);
                // 2.2 将秒杀库存放入redis
                redisTemplateStockCount.boundValueOps("seckillGoods" + seckillGoods.getId()).set(seckillGoods.getStockCount() + "");
            }
            System.out.println("从数据库中读取数据装入缓存");
        } else {
            System.out.println("从缓存中读取数据");
        }
        return seckillGoodsList;

    }

    public TbSeckillGoods findOneFromRedis(Long id) {
        System.out.println("根据秒杀商品ID从缓存中读取");
        return (TbSeckillGoods) redisTemplate.boundHashOps("seckillGoods").get(id);
    }
}

SeckillOrderService

package com.boxuegu.seckillorder.service;

import com.boxuegu.seckillorder.entity.IdWorker;
import com.boxuegu.seckillorder.mapper.TbSeckillGoodsMapper;
import com.boxuegu.seckillorder.mapper.TbSeckillOrderMapper;
import com.boxuegu.seckillorder.pojo.TbSeckillGoods;
import com.boxuegu.seckillorder.pojo.TbSeckillOrder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class SeckillOrderService {

    @Autowired
    private TbSeckillOrderMapper seckillOrderMapper;

    @Autowired
    private RedisTemplate redisTemplateStockCount;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TbSeckillGoodsMapper seckillGoodsMapper;


    @Autowired
    private IdWorker idWorker;

    @Autowired
    RabbitTemplate rabbitTemplate;

    public void submitOrder(Long seckillId, String userId) {
        // 1. 判断缓存中是否有库存
        String stockCountStr = (String) redisTemplateStockCount.boundValueOps("seckillGoods" + seckillId).get();
        if (stockCountStr != null && Long.parseLong(stockCountStr) > 0) {
            // 2. 预减库存
            Long stockCount = redisTemplateStockCount.boundValueOps("seckillGoods" + seckillId).decrement(1);
            if (stockCount >= 0) {
                // 3. 根据秒杀ID查询商品信息
                TbSeckillGoods seckillGoods = (TbSeckillGoods) redisTemplate.boundHashOps("seckillGoods").get(seckillId);
                if (seckillGoods != null) {
                    //4.向数据中保存订单信息
                    TbSeckillOrder seckillOrder = new TbSeckillOrder();
                    seckillOrder.setId(idWorker.nextId());
                    seckillOrder.setSeckillId(seckillId);
                    seckillOrder.setMoney(seckillGoods.getCostPrice());
                    seckillOrder.setUserId(userId);
                    seckillOrder.setSellerId(seckillGoods.getSellerId());//商家ID
                    seckillOrder.setCreateTime(new Date());
                    seckillOrder.setStatus("0");//状态改变
                    //5.保存订单
                    int result = 0;
                    try {
                        result = seckillOrderMapper.insert(seckillOrder);
                    } catch (Exception e) {
                        //库存的回滚
                        redisTemplateStockCount.boundValueOps("seckillGoods" + seckillId).increment(1);
                    }
                    if (result > 0) {
                        /*//6. 修改数据库库存
                        seckillGoodsMapper.updateStockCountByPrimaryKey(seckillId);   //更新数据库
                        System.out.println("商品同步到数据库..." + System.currentTimeMillis());*/
                        //发送MQ
                        Map map = new HashMap();
                        map.put("seckillId", seckillId);
                        rabbitTemplate.convertAndSend("seckillOrder_topic_exchange", "seckillOrder.submitOrder", map);
                    } else {
                        //库存的回滚
                        redisTemplateStockCount.boundValueOps("seckillGoods" + seckillId).increment(1);
                        System.out.println("保存订单失败.");
                    }
                }
            } else {
                redisTemplateStockCount.boundValueOps("seckillGoods" + seckillId).set("0");
                System.out.println("商品已卖完.");
            }
        } else {
            System.out.println("商品已卖完.");
        }
    }
}

消费端
image.png

SeckillOrder_Consumer

package com.boxuegu.seckillorder.consumer;

import com.boxuegu.seckillorder.mapper.TbSeckillGoodsMapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class SeckillOrder_Consumer {
    @Autowired
    TbSeckillGoodsMapper seckillGoodsMapper;

    @RabbitListener(queues = {"seckillOrder_queue"})
    public void receive(Map map, Message message, Channel channel) {
        //1.获取消息
        Long seckillId = (Long) map.get("seckillId");
        //2.扣减库存
        int result = 0;
        try {
            result = seckillGoodsMapper.updateStockCountByPrimaryKey(seckillId);
        } catch (Exception e) {
            System.out.println("修改库存失败,人工处理");
        }
        if (result > 0) {
            System.out.println("修改库存成功");
        } else {
            System.out.println("修改库存失败,人工处理");
        }
    }
}

评论

暂无评论