SpringBoot整合RabbitMQ 简单示例

引入依赖jar包

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

引入配置

@Configuration
public class RabbitConfig {

    final static String message = "sanguo.message";
    final static String message2 = "sanguo.message2";

    final static String TOPIC_EXCHANGE ="exchange";

    @Bean
    public Queue queue1() {
        return new Queue(message);
    }

    @Bean
    public Queue queue2() {
        return new Queue(message2);
    }

    @Bean
    TopicExchange exchange() {
        return new TopicExchange(TOPIC_EXCHANGE);
    }

    @Bean
    Binding bindingExchangeMessages(Queue queue1, TopicExchange exchange) {
        System.out.println(queue1.getName());
        return BindingBuilder.bind(queue1).to(exchange).with("sanguo.#");
    }

    @Bean
    Binding bindingExchangeMessage(Queue queue2, TopicExchange exchange) {
        System.out.println(queue2.getName());
        return BindingBuilder.bind(queue2).to(exchange).with("sanguo.message");
    }
}
这里做个笔记,RabbitMQ是通过交换机给queue发消息,但是中间还会通过RoutingKey进行过滤,BindingBuilder.bind(queue2).to(exchange).with(“sanguo.message”) 这句话的意思就是,通过交换机exchange发送的消息,满足RoutingKey条件的(sanguo.message)会被转发到queue2里面

下面是具体的消息发送

@Component
public class HelloSender {

    @Autowired
    private AmqpTemplate rabbitTemplate;

    public void send() {
        String context = "hello " + LocalDateTime.now();
        System.out.println("Sender : " + context);
        this.rabbitTemplate.convertAndSend("exchange","sanguo.aaa", context);
        //交换机,key,具体内容
    }
}

接收端–记得也要引入上面的依赖

@Component
@RabbitListener(queues = "sanguo.message")
public class HelloReceiver {
    //这里接收类型可以指定一个对象
    @RabbitHandler
    public void process(String hello) {
        System.out.println("Receiver  : " + hello);
    }

}

配置文件(接收端和发送端都需要)

spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值