SpringBoot和RabbitMQ整合

SpringBoot和RabbitMQ整合,第1张

SpringBoot和RabbitMQ整合 导入依赖

    org.springframework.boot
    spring-boot-starter-amqp
项目结构

编写yml文件
spring:
  rabbitmq:
#    地址
    host: 172.20.10.7
#    服务器端口
    port: 5672
#    账号
    username: guest
#    密码
    password: llh123456
#    SSL
    virtual-host: /
编写配置类
package com.guigu.www.springboot_rabbitmq.config;


import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {

    
    @Bean
    public Queue createQueue(){
        
        return new Queue("topics_springBoot");
    }

    
    @Bean
    public TopicExchange createTopicExchange(){
        
        return new TopicExchange("topics_springBoot_exchange");
    }

    
    @Bean
    public Binding binding(){
        
        return BindingBuilder.bind(createQueue()).to(createTopicExchange()).with("operation.#");
    }
}
编写接收者
package com.guigu.www.springboot_rabbitmq.consumer;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class TopicsConsumer {
    
    @RabbitListener(queues = "topics_springBoot")
    public void ConsumerMassges(Object obj){
        System.out.println(obj);
    }
}

启动SpringBootRabbitmqApplication

测试发布者
package com.guigu.www.springboot_rabbitmq;

import org.junit.jupiter.api.Test;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;

@SpringBootTest
class SpringBootRabbitmqApplicationTests {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Test
    void contextLoads() {
        
        rabbitTemplate.convertAndSend("topics_springBoot_exchange","operation.delete","删除成功!!!");
    }

}
运行结果:

接收类:

org.springframework.amqp.core.Message

接受消息:

(Body:'删除成功!!!' MessageProperties [headers={}, contentType=text/plain, contentEncoding=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=false, receivedExchange=topics_springBoot_exchange, receivedRoutingKey=operation.delete, deliveryTag=1, consumerTag=amq.ctag-krNfa2dtQnyYFgJLZcmR-g, consumerQueue=topics_springBoot])
附上工程链接,仅供学习参考!!!

springBoot_rabbitmq.zip - 蓝奏云文件大小:94.4 K|https://llh317.lanzout.com/i7Lnfy9aibc

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5691649.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-17
下一篇2022-12-17

发表评论

登录后才能评论

评论列表(0条)

    保存