美文网首页
Spring Boot集成RabbitMQ(一)

Spring Boot集成RabbitMQ(一)

作者: wencai | 来源:发表于2018-07-10 11:40 被阅读0次

RabbitMQ是以AMQP协议实现的一种中间件产品,几乎覆盖主流的企业级技术平台。本文仅通过一个demo介绍生产者、消费者及消息队列。

一、安装Erland和RabbitMQ

  目前维护的RabbitMQ版本系列不支持早于19.3的 Erlang / OTP版本。3.7.7之前的 RabbitMQ 版本不支持Erlang / OTP 21或更新版本。

二、引入maven依赖并配置连接信息

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
            <version>2.0.1.RELEASE</version>
        </dependency>
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

三、构建生产者、消费者、消息队列

生产者:

@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);//指明要发送到的消息队列
    }
}

消费者:

@Component
@RabbitListener(queues = "hello")//指明接受消息的消息队列
public class Receiver {

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

消息队列:

@Configuration
public class RabbitConfig {

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

}

只要执行生产者的send(),就可发送接受消息。

相关文章

网友评论

      本文标题:Spring Boot集成RabbitMQ(一)

      本文链接:https://www.haomeiwen.com/subject/ecjfpftx.html