SoFunction
Updated on 2025-05-13

Recording of the reliability and performance improvement of the process of integrating RabbitMQ in Spring Boot

1. Environmental preparation

Install RabbitMQ

  • Download the installation package of the corresponding operating system (such as Windows, Linux, etc.) on the official website and follow the installation wizard to complete the installation.
  • After the installation is complete, start the RabbitMQ service. On Windows, you can find the RabbitMQ Server in the service list and start it; on Linux, you can start it through the command line, for examplesystemctl start rabbitmq-server(The specific commands may vary by Linux distribution).
  • By default, RabbitMQ uses port 5672 for communication. Can be accessed through the browserhttp://localhost:15672(The default username and password are guest/guest) to access the RabbitMQ management interface and view queues, switches and other information.

Add Spring Boot Dependencies

In Spring Boot ProjectAdd RabbitMQ-related dependencies to the file. For example:

<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

This dependency will automatically introduce RabbitMQ's client library and Spring AMQP (Advanced Message Queuing Protocol)-related modules to facilitate us to operate RabbitMQ in Spring Boot.

2. Configure RabbitMQ

Configure in the or file

Show

=localhost
=5672
=guest
=guest

Here is the address, port, and login username and password of the RabbitMQ server. If the RabbitMQ server is deployed on another machine, you need tolocalhostReplace with the corresponding IP address.

Example

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

Advanced configuration (optional)

Connection pool configurationIf your application needs to interact with RabbitMQ frequently, you can improve performance by configuring a connection pool. For example

=3
-concurrency=10

Here, the minimum number of threads in the consumer thread pool is 3 and the maximum number of threads is 10. These parameters can be adjusted according to actual business needs.

Message confirmation mechanism configurationTo ensure that messages are sent reliably to the RabbitMQ server, the message acknowledgement mechanism can be enabled

-confirms=true

When the message is successfully sent to the RabbitMQ server, the server will send a confirmation message to the producer.

3. Producer code implementation

Create a RabbitMQ configuration class (optional)

If you need to customize some RabbitMQ configurations, such as switches, queues, etc., you can create a configuration class. For example

import .*;
import ;
import ;
@Configuration
public class RabbitMQConfig {
    // Define the queue    @Bean
    public Queue myQueue() {
        return new Queue("myQueue", true); // The second parameter indicates whether it is persisted    }
    // Define the switch    @Bean
    public DirectExchange myExchange() {
        return new DirectExchange("myExchange", true, false);
    }
    // Bind queues and switches    @Bean
    public Binding myBinding() {
        return (myQueue()).to(myExchange()).with("myRoutingKey");
    }
}

In this example, a name is definedmyQueuea queue namedmyExchangeDirectExchange (DirectExchange) and passes the routing keymyRoutingKeyBind the queue to the switch.

Create a producer class

useRabbitTemplateCome and send a message. For example:

import ;
import ;
import ;
@Component
public class RabbitMQProducer {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    public void sendMessage(String message) {
        ("myExchange", "myRoutingKey", message);
    }
}

In this example, by callingsendMessageMethod, send the message to the namemyExchangeand specify the routing key asmyRoutingKey. RabbitMQ will route messages to the corresponding queue according to the routing key.

4. Consumer code implementation

Create a consumer class

use@RabbitListenerAnnotation to listen for messages in the queue. For example:

import ;
import ;
@Component
public class RabbitMQConsumer {
    @RabbitListener(queues = "myQueue")
    public void receiveMessage(String message) {
        ("Received message: " + message);
    }
}

In this example,RabbitListenerThe annotation specifies the queue name to be listened to asmyQueue. When a message arrives at the queue,receiveMessageThe method will be called and the received message is printed.

Manual confirmation message (optional)

By default, Spring Boot uses automatic acknowledgement mode, that is, after a consumer receives a message, RabbitMQ will automatically believe that the message has been successfully processed. If you need to manually confirm the message, you can set it in the configuration class:

-mode=manual

Then in the consumer code,ChannelManual confirmation message:

import ;
import ;
import ;
import ;
@Component
public class RabbitMQConsumer {
    @RabbitListener(queues = "myQueue")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws Exception {
        ("Received message: " + message);
        // Manual confirmation of the message        (tag, false);
    }
}

In this example,ChannelofbasicAckMethod to manually confirm the message. If the message processing fails, you can call itbasicNackMethod reject message.

V. Test

Start the project

Start the Spring Boot project and make sure the RabbitMQ service is running.

Send a message

Calling the producer class in the codesendMessageMethod, send a message. For example:

@SpringBootApplication
public class RabbitMQApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = (, args);
        RabbitMQProducer producer = ();
        ("Hello, RabbitMQ!");
    }
}

View consumer output

Observe the console output of the consumer class to confirm whether the message was successfully received. If everything works fine, you should see an output similar to the following:

Received message: Hello, RabbitMQ!

Through the above steps, the basic operations of Spring Boot integrating RabbitMQ can be completed to realize the sending and receiving of messages.

This is the article about the reliability and performance improvement of Spring Boot integration RabbitMQ process. For more related Spring Boot integration RabbitMQ content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!