lee 1933 0 2017-03-14 22:16:06

文章位置:左搜> 编程技术> 正文

Java编程中Spring Boot整合RabbitMQ实现消息中间件RabbitMQ的使用

 1 主要用spring-boot-starter-amqp来整合RabbitMQ和SpringBoot

 2 pom.xml文件中加入依赖
 

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

 3编写配置文件application.yml

spring:
  application:
    name: rabbitmq-test
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest
4 Java编程中编写Sender并使用注解@Component注册为spring框架容器组件
@Component
public class Sender {
    @Autowired
    private AmqpTemplate amqpTemplate;

    public void send() throws Exception {
        String message= "hello" + new Date();
        System.out.println("Sender:"+context);
        this.amqpTemplate.convertAndSend("test_queue_name",message);
    }
}
5 Java编程中编写Reveiver并使用注解@Component注册为spring框架容器组件同时监听队列hello,并用RabbitHandler来处理请求。queues = "test_queue_name"这里的test_queue_name就是发送消息时候的队列名称
@Component
@RabbitListener(queues = "test_queue_name")
public class Receiver {

    @RabbitHandler
    public void process(String message){
        System.out.println("Receiver:"+message);
    }
}
6Java编程中编写刚刚用到的hello队列的配置类
@Configuration
public class RabbitConfig {
    @Bean
    public Queue helloQueue() {
        return new Queue("test_queue_name");
    }
}
7 Java编程中编写单元测试类Test,调用Sender的方法发送message,这样Receiver就能自动监听并在主类哪里输出了
@SpringBootTest(classes = Application.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class Test {

    @Autowired
    private Sender sender;

    @org.junit.Test
    public void hello() throws Exception {
        sender.send();
    }
}