程序员从入门到放弃程序员技术干货

简简单单spring-boot整合RabbitMQ

2017-12-30  本文已影响123人  虾游于海

RabbitMQ是比较常用的AMQP实现,这篇文章是一个简单的Spring boot整合RabbitMQ的教程。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
spring:
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: username
    password: password
    virtual-host: /
@Configuration
public class Aqueue {
    @Bean
    public Queue queue() {
        return new Queue("good");
    }

}
/**
 * 定义一个生产者
 * @author LiDong
 */
@RestController
@RequestMapping("/test")
public class SendController {
    @Autowired
    private AmqpTemplate template;

    @GetMapping
    public String testSend() {
        // 使用AmqpTemplate发送消息
        template.convertAndSend("good", "good");
        return "success";
    }
}
@Component
public class Consumer {
    /**
     * 定义一个消费者
     * @param message
     */
    @RabbitListener(queues = "good")
    public void handler(String message) {
        System.out.println("recive message from " + message);
    }
}

启动测试,在浏览器中输入 http://localhost:8080/test即可发送一条消息到队列中。 该对列可以被消费者处理

完整的示例代码,参见 github
另外,Spring Boot整合ActiveMQ也非常简单,参见Spring Boot 整合ActiveMQ的过程

上一篇 下一篇

猜你喜欢

热点阅读