spring boot整合rabbitmq(5种)

原文:https://blog.csdn.net/qq_38762237/article/details/89433506

依赖

​ org.springframework.boot ​ spring-boot-starter-amqp

application.yml

spring:
rabbitmq:
​ host: 127.0.0.1
​ username: tellsea
​ password: 123456
​ virtual-host: /tellsea-host

simple消息模型

发送消息

@Autowired
private AmqpTemplate amqpTemplate;

@Test
public void simple() throws InterruptedException {
	String msg = "RabbitMQ simple ...";
	for (int i = 0; i < 10; i++) {
		amqpTemplate.convertAndSend("spring.simple.queue", msg + i);
	}
	Thread.sleep(5000);
}

接收消息

@Component
public class SimpleListener {
// 通过注解自动创建 spring.simple.queue 队列
@RabbitListener(queuesToDeclare = @Queue("spring.simple.queue"))
public void listen(String msg) {
    System.out.println("SimpleListener listen 接收到消息:" + msg);
}
}

work消息模型

在刚才的基本模型中,一个生产者,一个消费者,生产的消息直接被消费者消费。比较简单。

Work queues,也被称为(Task queues),任务模型。

当消息处理比较耗时的时候,可能生产消息的速度会远远大于消息的消费速度。长此以往,消息就会堆积越来越多,无法及时处理。此时就可以使用work 模型:让多个消费者绑定到一个队列,共同消费队列中的消息。

队列中的消息一旦消费,就会消失,因此任务是不会被重复执行的

发送消息
@Test
public void work() throws InterruptedException {
    String msg = "RabbitMQ simple ...";
    for (int i = 0; i < 10; i++) {
        amqpTemplate.convertAndSend("spring.work.queue", msg + i);
    }
    Thread.sleep(5000);
}
接收消息
@Component
public class WorkListener {

// 通过注解自动创建 spring.work.queue 队列
@RabbitListener(queuesToDeclare = @Queue("spring.work.queue"))
public void listen(String msg) {
    System.out.println("WorkListener listen 接收到消息:" + msg);
}

// 创建两个队列共同消费
@RabbitListener(queuesToDeclare = @Queue("spring.work.queue"))
public void listen2(String msg) {
    System.out.println("WorkListener listen2 接收到消息:" + msg);
  }
}

订阅模型-Fanout

Fanout,也称为广播。在广播模式下,消息发送流程是这样的:

1) 可以有多个消费者

2) 每个消费者有自己的queue(队列)
3) 每个队列都要绑定到Exchange(交换机)
4) 生产者发送的消息,只能发送到交换机,交换机来决定要发给哪个队列,生产者无法决定。

5) 交换机把消息发送给绑定过的所有队列
6) 队列的消费者都能拿到消息。实现一条消息被多个消费者消费

发送消息
@Test
public void fanout() throws InterruptedException {
    String msg = "RabbitMQ fanout ...";
    for (int i = 0; i < 10; i++) {
        // 这里注意细节,第二个参数需要写,不然第一个参数就变成routingKey了
        amqpTemplate.convertAndSend("spring.fanout.exchange", "", msg + i);
    }
    Thread.sleep(5000);
}
接收消息
/**
 * Fanout:广播,将消息交给所有绑定到交换机的队列,每个消费者都会收到同一条消息
 */
@Component
public class FanoutListener {

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "spring.fanout.queue", durable = "true"),
            exchange = @Exchange(
                    value = "spring.fanout.exchange",
                    ignoreDeclarationExceptions = "true",
                    type = ExchangeTypes.FANOUT
            )
    ))
    public void listen(String msg) {
        System.out.println("FanoutListener listen 接收到消息:" + msg);
    }

    // 队列2(第二个人),同样能接收到消息
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "spring.fanout2.queue", durable = "true"),
            exchange = @Exchange(
                    value = "spring.fanout.exchange",
                    ignoreDeclarationExceptions = "true",
                    type = ExchangeTypes.FANOUT
            )
    ))
    public void listen2(String msg) {
        System.out.println("FanoutListener listen2 接收到消息:" + msg);
    }
}

订阅模型-Direct

在Fanout模式中,一条消息,会被所有订阅的队列都消费。但是,在某些场景下,我们希望不同的消息被不同的队列消费。这时就要用到Direct类型的Exchange。

在Direct模型下:

  • 队列与交换机的绑定,不能是任意绑定了,而是要指定一个RoutingKey(路由key)

  • 消息的发送方在 向 Exchange发送消息时,也必须指定消息的 RoutingKey

  • Exchange不再把消息交给每一个绑定的队列,而是根据消息的Routing Key进行判断,只有队列的Routingkey与消息的 Routing key完全一致,才会接收到消息

发送消息

@Test
public void direct() throws InterruptedException {
    String msg = "RabbitMQ direct ...";
    for (int i = 0; i < 10; i++) {
        amqpTemplate.convertAndSend("spring.direct.exchange", "direct", msg + i);
    }
    Thread.sleep(5000);
}

接收消息

/**
 * Direct:定向,把消息交给符合指定routing key 的队列
 */
@Component
public class DirectListener {

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "spring.direct.queue", durable = "true"),
            exchange = @Exchange(
                    value = "spring.direct.exchange",
                    ignoreDeclarationExceptions = "true"
            ),
            key = {"direct"}
    ))
    public void listen(String msg) {
        System.out.println("DirectListener listen 接收到消息:" + msg);
    }

    // 队列2(第二个人),key值不同,接收不到消息
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "spring.direct2.queue", durable = "true"),
            exchange = @Exchange(
                    value = "spring.direct.exchange",
                    ignoreDeclarationExceptions = "true"
            ),
            key = {"direct-test"}
    ))
    public void listen2(String msg) {
        System.out.println("DirectListener listen2 接收到消息:" + msg);
    }
}

订阅模型-Topic

发送消息

@Test
public void topic() throws InterruptedException {
    amqpTemplate.convertAndSend("spring.topic.exchange", "user.insert", "新增用户");
    amqpTemplate.convertAndSend("spring.topic.exchange", "user.delete", "删除用户");
    amqpTemplate.convertAndSend("spring.topic.exchange", "student.insert", "新增学生");
    amqpTemplate.convertAndSend("spring.topic.exchange", "student.delete", "删除学生");
    Thread.sleep(5000);
}
接收消息
/**
 * Topic:通配符,把消息交给符合routing pattern(路由模式) 的队列
 */
@Component
public class TopicListener {

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "spring.topic.queue", durable = "true"),
            exchange = @Exchange(
                    value = "spring.topic.exchange",
                    ignoreDeclarationExceptions = "true",
                    type = ExchangeTypes.TOPIC
            ),
            key = {"user.*"}
    ))
    public void listen(String msg) {
        System.out.println("TopicListener User 接收到消息:" + msg);
    }

    // 通配规则不同,接收不到消息
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "spring.topic.queue", durable = "true"),
            exchange = @Exchange(
                    value = "spring.topic.exchange",
                    ignoreDeclarationExceptions = "true",
                    type = ExchangeTypes.TOPIC
            ),
            key = {"student.*"}
    ))
    public void listen2(String msg) {
        System.out.println("TopicListener Student 接收到消息:" + msg);
    }
}

作者:小海绵-Tellsea
来源:CSDN
原文:https://blog.csdn.net/qq_38762237/article/details/89433506

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring BootRabbitMQ整合可以通过使用Spring AMQP实现。下面是一个简单的步骤: 1. 添加依赖:在`pom.xml`文件中添加以下依赖关系: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> ``` 2. 配置RabbitMQ连接:在`application.properties`或`application.yml`文件中配置RabbitMQ的连接信息,例如: ```properties spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 spring.rabbitmq.username=guest spring.rabbitmq.password=guest ``` 3. 创建生产者:创建一个简单的生产者,用于向RabbitMQ发送消息。你可以使用`RabbitTemplate`类来发送消息,例如: ```java import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class MessageProducer { @Autowired private RabbitTemplate rabbitTemplate; public void sendMessage(String message) { rabbitTemplate.convertAndSend("exchangeName", "routingKey", message); } } ``` 4. 创建消费者:创建一个简单的消费者,用于接收RabbitMQ发送的消息。你可以使用`@RabbitListener`注解来定义一个消息监听器,例如: ```java import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component public class MessageConsumer { @RabbitListener(queues = "queueName") public void receiveMessage(String message) { System.out.println("Received message: " + message); } } ``` 5. 启用RabbitMQ:通过在Spring Boot应用程序的主类上添加`@EnableRabbit`注解来启用RabbitMQ功能,例如: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.amqp.rabbit.annotation.EnableRabbit; @SpringBootApplication @EnableRabbit public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 这就是整合Spring BootRabbitMQ的基本步骤。你可以根据自己的需求进行更多的高级配置和定制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值