springboot 集成 rabbitMQ

rabbitMQ:先放两张图 方便记忆

视频教程:https://study.163.com/course/courseMain.htm?courseId=1004576013

环境:首先要安装好 rabbitMQ

 

springboot 集成 rabbitMQ还是挺简单的。

rabbitMQ的原理是(个人理解),自己做好的demo已经保存到百度网盘下。

生产者:发送消息给交换器 exchange

消费者:监听队列消息

队列:队列和交换器绑定

交换器:生产者发送消息给路由器 交换器根据规则发送消息到队列

 

1.创建一个springboot项目 依赖:web,rabbitMQ

2.配置properties

spring.application.name=rabbitMQ
server.port=8080

spring.rabbitmq.host=172.17.0.50
spring.rabbitmq.port=5672
spring.rabbitmq.username=hanhao
spring.rabbitmq.password=hanhao

第二种配置:direct

spring.application.name=rabbitDirectProvider
server.port=9999
spring.rabbitmq.host=172.17.0.50
spring.rabbitmq.port=5672
spring.rabbitmq.username=hanhao
spring.rabbitmq.password=hanhao

mq.config.exchange=log.direct

第三种:topic 匹配模式

消费者:

package com.bicon.directconsumer;

import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(bindings=@QueueBinding(
        value=@Queue(value="${mq.config.queue.error}",autoDelete="true"),
        exchange=@Exchange(value="${mq.config.exchange}",type=ExchangeTypes.TOPIC),
        key="*.log.error"
        )
        )
public class ErrorReceive {
    
    @RabbitHandler
    public void process(String msg) {
        System.out.println("接收到ERROR:"+msg);
    }

}

生产者:

package com.bicon.directprovider;

import javax.validation.Valid;

import net.bytebuddy.asm.Advice.This;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class OrderSender {

    @Autowired
    private AmqpTemplate rabbitTemplate;
    
    @Value("${mq.config.exchange}")
    private String exchange;
    
    public void send(String msg){
        this.rabbitTemplate.convertAndSend(this.exchange,"order.log.info",msg);
        this.rabbitTemplate.convertAndSend(this.exchange,"order.log.debug",msg);
        this.rabbitTemplate.convertAndSend(this.exchange,"order.log.warn",msg);
        this.rabbitTemplate.convertAndSend(this.exchange,"order.log.error",msg);
    }
}

 

 

 

 

 

 

 

 

posted on 2018-11-16 17:13  爱屋及乌88  阅读(143)  评论(0编辑  收藏  举报

导航