欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springBoot 集成RabbitMq Demo

程序员文章站 2022-07-12 12:29:04
...

pom文件添加依赖

<dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-amqp</artifactId>

    </dependency>

properties/yml文件添加

## rabbitmq config

spring.rabbitmq.host=localhost

spring.rabbitmq.port=5672

spring.rabbitmq.username=root

spring.rabbitmq.password=123456

创建Rabbit配置类,用来配置队列,交换器,路由等高级信息

@Configuration

public class RabbitConfig {

     @Bean

     public Queue firstQueue() {

       // 创建一个队列,名称为:myTopic

        return new Queue("myTopic");

     }

创建消息的生产者

@Component

public class Sender {

     @Resource

     private AmqpTemplate rabbitTemplate;

     public void send() {

      rabbitTemplate.convertAndSend("myTopic", "this a messages !!!");

     }

}

创建消息的消费者

@Component

//定义该类需要监听的队列

@RabbitListener(queues = "myTopic")

public class Receiver {

    @RabbitHandler  //指定对消息的处理

    public void process(String msg) {

        System.out.println("receive msg : " + msg);

 }

}

测试

@RunWith(SpringRunner.class)

@SpringBootTest(classes = App.class)

public class RabbitmqTest {

    @Resource

    private Sender sender;

     @Test

     public void testRabbitmq() throws Exception {

         sender.send();

     }

}