RabbitMQ 生产消息并放入队列

前提已有 Exchange, Queue, Routing Key, 可以在 web 页面点击鼠标创建, 也可在消费端通过代码自动创建

web 页面配置步骤: https://www.cnblogs.com/huanggy/p/9695712.html

消费端: https://www.cnblogs.com/huanggy/p/9695934.html

假设要发送订单消息, 具体流程如下:

1, 创建 springboot 项目, 添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

2, application.properties

# rabbitmq
spring.rabbitmq.addresses=*******:5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.virtual-host=/
spring.rabbitmq.connection-timeout=15000

3, 建立消息内容对用的实体类(这里是 order ), 这个实体必须实现序列化接口, 因为这个对象将要进行网络传输, 会发送到 rabbitmq 服务器

4, 发送消息

  1) 注入 RabbitTemplate

  2) 调用 void convertAndSend(String exchange, String routingKey, final Object object, CorrelationData correlationData) throws AmqpException 方法来发送消息

@Component
public class OrderSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    
    public void send(Order order) throws Exception {
        // 自定义消息唯一标识
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(order.getMsgId());
        // exchange,  routing, 消息内容,  消息唯一标识
        rabbitTemplate.convertAndSend("order-exchange", "order.rk1", order, correlationData);
    }
}

5, 测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
    
    @Autowired
    private OrderSender orderSender;

    @Test
    public void contextLoads() {
    }
    
    @Test
    public void testSend1() throws Exception {
        Order order = new Order();
        order.setId(1);
        order.setName("测试订单1");
        order.setMsgId(UUID.randomUUID().toString());
        order.setCreateTime(new Date());
        orderSender.send(order);
    }

}

6, 管控台查看

 

posted @ 2018-09-24 15:59  huanggy  阅读(3628)  评论(0编辑  收藏  举报