Spring Boot应用程序集成RabbitMQ

以下是一个Spring Boot应用程序集成RabbitMQ的示例,展示了如何发送和消费消息。我们将使用Spring AMQP模块来实现这个示例。

创建Spring Boot项目

首先,确保你在项目的pom.xml文件中添加了以下依赖:

    <dependencies>
        <!-- Spring Boot Starter AMQP -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
            <version>2.3.12.RELEASE</version>
        </dependency>

        <!-- Spring Boot Starter Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.3.12.RELEASE</version>
        </dependency>
    </dependencies>

配置RabbitMQ

在项目的application.yml文件中添加RabbitMQ相关的配置:

spring:
  # 模拟控制平台 rabbitmq 信息
  rabbitmq:
    virtual-host: /
    host: 127.0.0.1
    port: 5672
    username: rabbitmq
    password: rabbitmq
    listener:
      simple:
        concurrency: 1 #最小的消费者数量
        max-concurrency: 100 #最大的消费者数量
        acknowledge-mode: manual # 手动应答
        prefetch: 1
      connection-timeout: 0

创建配置类

创建一个配置类来定义队列、交换机和绑定:

package com.example.rabbitmqdemo.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {

    public static final String QUEUE_NAME = "demo_queue";
    public static final String EXCHANGE_NAME = "demo_exchange";
    public static final String ROUTING_KEY = "demo_routing_key";

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMessageConverter(new Jackson2JsonMessageConverter());
        return template;
    }

    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(new Jackson2JsonMessageConverter());
        return factory;
    }

    @Bean
    public Queue queue() {
        return new Queue(QUEUE_NAME, false);
    }

    @Bean
    public TopicExchange exchange() {
        return new TopicExchange(EXCHANGE_NAME);
    }

    @Bean
    public Binding binding(Queue queue, TopicExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(ROUTING_KEY);
    }
}


编写生产者代码

创建一个RabbitMQ生产者类,用于发送消息:

package com.example.rabbitmqdemo.producer;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.example.rabbitmqdemo.config.RabbitMQConfig.EXCHANGE_NAME;
import static com.example.rabbitmqdemo.config.RabbitMQConfig.ROUTING_KEY;

@Service
public class RabbitMQProducer {

    private final RabbitTemplate rabbitTemplate;

    @Autowired
    public RabbitMQProducer(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    public void sendMessage(String message) {
        rabbitTemplate.convertAndSend(EXCHANGE_NAME, ROUTING_KEY, message);
    }
}

编写消费者代码

创建一个RabbitMQ消费者类,用于消费消息:

package com.example.rabbitmqdemo.consumer;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import static com.example.rabbitmqdemo.config.RabbitMQConfig.QUEUE_NAME;

@Service
public class RabbitMQConsumer {

    @RabbitListener(queues = QUEUE_NAME)
    public void consumeMessage(String message) {
        System.out.println("Received message: " + message);
    }
}

创建控制器

创建一个控制器来触发消息的发送:

package com.example.rabbitmqdemo.controller;

import com.example.rabbitmqdemo.producer.RabbitMQProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RabbitMQController {

    private final RabbitMQProducer rabbitMQProducer;

    @Autowired
    public RabbitMQController(RabbitMQProducer rabbitMQProducer) {
        this.rabbitMQProducer = rabbitMQProducer;
    }

    @GetMapping("/send")
    public String sendMessage(@RequestParam("message") String message) {
        rabbitMQProducer.sendMessage(message);
        return "Message sent to RabbitMQ!";
    }
}

Spring Boot 主类

创建Spring Boot应用程序的主类:

package com.example.rabbitmqdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class RabbitMQDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(RabbitMQDemoApplication.class, args);
    }
}

运行应用程序

启动Spring Boot应用程序,确保RabbitMQ服务器正在运行。然后,使用浏览器或工具(如Postman)访问以下URL以发送消息:

http://localhost:8080/send?message=HelloRabbitMQ

验证消费

你应该能够在控制台上看到消费者接收到的消息输出:

Received message: HelloRabbitMQ

解释

  1. 依赖管理

    • 使用Spring Boot Starter AMQP来简化RabbitMQ的集成。
    • 使用Spring Boot Starter Web来简化Web应用开发。
  2. 配置

    • application.yml中指定RabbitMQ服务器的地址和认证信息。
  3. 配置类

    • 使用@Configuration注解定义队列、交换机和绑定。
  4. 生产者服务

    • 使用RabbitTemplate来发送消息到指定的交换机和路由键。
  5. 消费者服务

    • 使用@RabbitListener注解来监听指定队列的消息并处理。
  6. 控制器

    • 创建一个简单的REST控制器来触发消息发送操作。

通过这个示例,你可以轻松地使用Spring Boot集成RabbitMQ来实现消息的发送和消费。

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值