【Spring Boot】Spring Boot之整合RabbitMQ并实现消息的发送和接收

一、项目配置

1)引入maven坐标

        <!--amqp-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-amqp</artifactId>
                <version>2.0.3.RELEASE</version>
            </dependency>

2)application.yml加入RabbitMQ的连接配置

spring.rabbitmq.host: localhost
spring.rabbitmq.port: 5672
spring.rabbitmq.username: guest
spring.rabbitmq.password: guest

 

二、消息的发送和接收

1)创建指定名称的消息队列

@Configuration
public class RabbitConfig {
    @Bean
    public Queue helloQueue() {
        return new Queue("hello");
    }
}

2)创建消息接收者

@Component
@RabbitListener(queues = "hello")
public class Receiver {
    @RabbitHandler
    public void process(String hello) {
        System.out.println("Receiver : " + hello);
    }
}

3)创建消息发送着

@Component
public class Sender {

    @Autowired
    private AmqpTemplate rabbitTemplate;

    public void send() {
        String context = "hello " + new Date();
        System.out.println("Sender : " + context);
        this.rabbitTemplate.convertAndSend("hello", context);
    }
}

 

4)创建发送消息的测试类

@RunWith(SpringRunner.class)
@WebAppConfiguration
@SpringBootTest
public class RabbitMQSenderTest {

    @Autowired
    private Sender sender;

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

}

 

posted @ 2019-09-06 07:47  N!CE波  阅读(3267)  评论(0编辑  收藏  举报