Skip to main content

Some common scenarios for using RabbitMQ in java web

Some common scenarios for using RabbitMQ in java web

1. Message broadcast : If you need to broadcast messages to multiple receivers, such as real-time notifications, advertising push, etc., you can use RabbitMQ's publish/subscribe mode. A message is published to an exchange and multiple queues subscribed to that exchange will receive the message.

2. Asynchronous task processing : When your application needs to process some time-consuming operations, such as sending emails, generating reports, processing images, etc., you can use RabbitMQ to put these tasks into the message queue, and then the background consumers for processing. This avoids blocking user requests and improves system response performance.

3. Distributed system communication : If your Java Web project is a distributed system and different services or modules need to communicate and collaborate, you can use RabbitMQ as the message broker. By sending messages to queues, different services can receive and process messages asynchronously, achieving decoupled and flexible system architecture.

4. Log processing : In large-scale Java Web projects, processing and storing logs is often a challenge. You can use RabbitMQ to send log messages to a message queue, and a dedicated consumer writes the logs to a database, file, or other storage medium. This decouples log processing from the application, improving performance and maintainability.

5. Event-driven architecture : In some cases, you may want to introduce event-driven architecture in your system. By using RabbitMQ, you can publish events as messages to a queue and have interested consumers subscribe to these events. This enables a loosely coupled system architecture and allows different modules to respond as needed.

1.1 How to userabbitmq to implement message propagation in Java web?

1. Install RabbitMQ: Follow the steps mentioned before to download, install and start RabbitMQ.

2. Add RabbitMQ client dependency: In your Java Web project, add the dependency of RabbitMQ client library. If you use Maven, you can add the following dependencies in your project's pom.xml file:

       1. <dependency>

2. <groupId>com.rabbitmq</groupId>

3. <artifactId>amqp-client</artifactId>

4. <version>5.12.0</version>

5. </dependency>



3. Create a connection and channel: In your code, use RabbitMQ's Java client library to create a connection and channel to the RabbitMQ server. The sample code is as follows:

       1. import com.rabbitmq.client.Connection;

2. import com.rabbitmq.client.Channel;

3. import com.rabbitmq.client.ConnectionFactory;

4.

5. public class RabbitMQUtils {

6. private final static String QUEUE_NAME = "my_queue";

7.

8. public static Connection getConnection() throws Exception {

9. ConnectionFactory factory = new ConnectionFactory();

10. factory.setHost("localhost");

11. factory.setUsername("guest");

12. factory.setPassword("guest");

13. return factory.newConnection();

14. }

15.

16. public static Channel getChannel(Connection connection) throws Exception {

17. return connection.createChannel();

18. }

19.

20. public static void closeConnection(Connection connection) throws Exception {

21. if (connection != null) {

22. connection.close();

23. }

24. }

25.

26. public static void closeChannel(Channel channel) throws Exception {

27. if (channel != null) {

28. channel.close();

29. }

30. }

31. }

32. /*

33. * host here refers to the host name or IP address of the RabbitMQ server used to establish a connection to the server. If you are running *RabbitMQ locally, you can set host to "localhost". 34.

34. *username and password are the credentials used for authentication to connect to the RabbitMQ server. rabbitMQ by default will

35. * Create a user named "guest" and set the password to "guest". These default credentials are used for development and testing purposes.

36. */

4. Publish the message: In your code, use the channel to publish the message to the switch . The sample code is as follows:

       1. import com.rabbitmq.client.Connection;

2. import com.rabbitmq.client.Channel;

3.

4. public class MessagePublisher {

5. public static void main(String[] args) {

6. try {

7. Connection connection = RabbitMQUtils.getConnection();

8. Channel channel = RabbitMQUtils.getChannel(connection);

9.

10. String message = "Hello, RabbitMQ!";

11. channel.basicPublish("", "my_exchange", null, message.getBytes());

12. System.out.println("Message published: " + message);

13.

14. RabbitMQUtils.closeChannel(channel);

15. RabbitMQUtils.closeConnection(connection);

16. } catch (Exception e) {

17. e.printStackTrace();

18. }

19. }

20. }

21. /*

22. * In the channel.basicPublish method, the parameters have the following meanings:

23. /* 1. First parameter: exchange name. An empty string is used here to indicate the default switch. The switch is responsible for routing messages

24. * By to one or more queues. If you specify a switch name, messages are routed according to the rules of the switch. If you use the empty string, * then the message will be sent directly to the specified queue(s).

25. *2. Second parameter: the routing key. This is the keyword used to route the message to a specific queue. It is matched against the rules and * bindings of the switch. Here, we send the message to the switch named "my_exchange".

26. *3. Third parameter: other properties of the message (message properties). Here we set it to null to indicate that there are no additional * properties. You can set the persistence, priority, expiration time, etc. of the message here. 27. *4.

27. *4. The fourth parameter: the content of the message (message body). The message body is the actual data to be delivered. Here, we use *message.getBytes() to convert a string message to a byte array.

28. */




5. Consume messages: In your code, create a consumer and subscribe to the queue to receive and process messages. The sample code is as follows:

       1. import com.rabbitmq.client.*;

2.

3. public class MessageConsumer {

4. public static void main(String[] args) {

5. try {

6. Connection connection = RabbitMQUtils.getConnection();

7. Channel channel = RabbitMQUtils.getChannel(connection);

8.

9. channel.queueDeclare("my_queue", false, false, false, null);

10. System.out.println("Waiting for messages...");

11.

12. DeliverCallback deliverCallback = (consumerTag, delivery) -> {

13. String message = new String(delivery.getBody());

14. System.out.println("Received message: " + message);

15. };

16. channel.basicConsume("my_queue", true, deliverCallback, consumerTag -> {});

17.

18. // Keep the consumer running

19. Thread.sleep(5000);

20.

21. RabbitMQUtils.closeChannel(channel);

22. RabbitMQUtils.closeConnection(connection);

23. } catch (Exception e) {

24. e.printStackTrace();

25. }

26. }

27. }

28. /*

29. * Here a queue named "my_queue" is declared using the channel.queueDeclare method. This queue will be used to receive messages.

30. * In the channel.queueDeclare method, the parameters have the following meanings:

31. *1. First parameter: queue name. This is the name of the queue to be declared. If the queue does not exist, a new queue * will be created. If the queue already exists, its properties will be checked to see if they match those declared.

32. *2. Second parameter: whether or not it is persistent (durable). If it is set to true, the queue is persistent, i.e., it will still exist after the * RabbitMQ server is restarted. If set to false, the queue is non-persistent, i.e., it will be deleted after a restart of the RabbitMQ * server. 33. *3.

33. *3. Third parameter: exclusive or not. If set to true, the queue can only be used by the current connection and * will be deleted automatically when the connection is closed. If set to false, the queue can be shared by multiple connections. 34. *4.

34. *4. Fourth parameter: whether to auto-delete. If set to true, the queue will be deleted automatically after the last consumer disconnects. If it is set to false, the queue will not be deleted automatically.

35. *5. Fifth parameter: other attributes. This is an optional parameter to pass other queue attributes. Here, we set it

36. * Set it to null to indicate that there are no other attributes.

37. * By calling the channel.queueDeclare method, we can declare a queue and create it when needed. This way, we can * subscribe to that queue in the consumer and start receiving and processing messages.

38. */


In this example, we create a simple message publisher and a message consumer. The publisher publishes messages to the exchange named "my_exchange" and the consumer subscribes to the queue named "my_queue" and processes messages as they are received.

2.1 How to use rabbitmq to implement asynchronous task processing in Java web?

1. First, make sure the RabbitMQ server has been installed and configured.

2. Add RabbitMQ dependencies to the Java Web project. You can use Maven to manage dependencies. Add the following dependencies to the project's pom.xml file:

       1. <dependency>

2. <groupId>com.rabbitmq</groupId>

3. <artifactId>amqp-client</artifactId>

4. <version>5.12.0</version>

5. </dependency>



3. Create a RabbitMQ connection factory and configure connection parameters, such as host name, port number, user name and password, etc.

       1. ConnectionFactory factory = new ConnectionFactory();

2. factory.setHost("localhost");

3. factory.setPort(5672);

4. factory.setUsername("guest");

5. factory.setPassword("guest");



4. Use the connection factory to create a RabbitMQ connection.

 
Connection connection = factory.newConnection();

5. Create a channel (Channel) and declare a task queue.

       1. Channel channel = connection.createChannel();

2. channel.queueDeclare("task_queue", true, false, false, null);



6. In Java Web, tasks that require asynchronous processing can be encapsulated into messages and sent to the task queue.

       1. String message = "Hello, RabbitMQ!";

2. channel.basicPublish("", "task_queue", MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());



7. Create a consumer to receive and process messages in the task queue.

       1. Consumer consumer = new DefaultConsumer(channel) {

2. @Override

3. public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {

4. String message = new String(body, "UTF-8");

5. System.out.println("Received message: " + message);

6. // Processing tasks

7. }

8. };

9.

10. channel.basicConsume("task_queue", true, consumer);



Through the above steps, you can use RabbitMQ to implement asynchronous task processing in Java Web. After sending a task message to the queue, the consumer will receive the message and process it.