当前位置:   article > 正文

Java中如何使用消息队列实现异步(ActiveMQ,RabbitMQ,Kafka)_java实现异步队例调用

java实现异步队例调用

一、ActiveMQ 示例

在 Java 中,可以使用消息队列实现异步处理。下面是一个简单的示例代码,用于说明如何使用 ActiveMQ 实现消息队列异步处理:

  1. 添加 ActiveMQ 依赖

在 pom.xml 文件中添加以下依赖:

<dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>activemq-all</artifactId>
    <version>5.16.3</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  1. 创建消息队列

创建一个名为 “TestQueue” 的消息队列,并配置 ActiveMQ 连接信息:

import javax.jms.*;
import org.apache.activemq.ActiveMQConnectionFactory;

public class TestQueue {
    public static void main(String[] args) throws Exception {
        // 创建连接工厂
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
        
        // 创建连接
        Connection connection = connectionFactory.createConnection();
        connection.start();
        
        // 创建会话
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        
        // 创建队列
        Queue queue = session.createQueue("TestQueue");
        
        // 创建生产者
        MessageProducer producer = session.createProducer(queue);
        
        // 发送消息
        for (int i = 0; i < 10; i++) {
            TextMessage message = session.createTextMessage("Message " + i);
            producer.send(message);
        }
        
        // 关闭连接
        connection.close();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  1. 创建消息消费者

创建一个消息消费者,并实现 MessageListener 接口,以便异步处理消息:

import javax.jms.*;
import org.apache.activemq.ActiveMQConnectionFactory;

public class TestConsumer implements MessageListener {
    public static void main(String[] args) throws Exception {
        // 创建连接工厂
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
        
        // 创建连接
        Connection connection = connectionFactory.createConnection();
        connection.start();
        
        // 创建会话
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        
        // 创建队列
        Queue queue = session.createQueue("TestQueue");
        
        // 创建消费者
        MessageConsumer consumer = session.createConsumer(queue);
        consumer.setMessageListener(new TestConsumer());
        
        // 等待消息
        Thread.sleep(5000);
        
        // 关闭连接
        connection.close();
    }
    
    @Override
    public void onMessage(Message message) {
        try {
            if (message instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) message;
                System.out.println("Received message: " + textMessage.getText());
            }
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  1. 运行代码

在命令行中分别执行 TestQueue 和 TestConsumer 两个类,可以看到生产者向消息队列发送了10条消息,并由消息消费者异步处理这些消息。

使用消息队列可以有效地实现异步处理,可以提高应用程序的性能和并发能力。在上述示例代码中,生产者通过创建消息并将其发送到队列中,而消费者则监听队列并异步处理接收到的消息。消息队列可以起到解耦作用,使得生产者和消费者之间的交互更加灵活和可靠,因为消息队列具有缓冲和异步处理的特点,即使某个消费者出现故障,也不会影响消息的传递和处理。

总的来说,消息队列是一种重要的异步通信机制,能够提高系统的可靠性和可伸缩性,适用于各种分布式系统和大规模应用程序。除了 ActiveMQ,还有其他很多优秀的消息队列实现,比如 RabbitMQ、Kafka 等。

二、RabbitMQ

  1. RabbitMQ 示例代码

在 Java 中,可以使用 RabbitMQ 的 Java 客户端实现消息队列的异步处理。下面是一个简单的示例代码,用于说明如何使用 RabbitMQ 实现消息队列异步处理:

  1. 添加 RabbitMQ 依赖

在 pom.xml 文件中添加以下依赖:

<dependency>
    <groupId>com.rabbitmq</groupId>
    <artifactId>amqp-client</artifactId>
    <version>5.12.0</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  1. 创建消息队列

创建一个名为 “TestQueue” 的消息队列,并配置 RabbitMQ 连接信息:

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class TestQueue {
    public static void main(String[] args) throws Exception {
        // 创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");
        
        // 创建连接
        Connection connection = connectionFactory.newConnection();
        
        // 创建通道
        Channel channel = connection.createChannel();
        
        // 创建队列
        channel.queueDeclare("TestQueue", false, false, false, null);
        
        // 发送消息
        for (int i = 0; i < 10; i++) {
            String message = "Message " + i;
            channel.basicPublish("", "TestQueue", null, message.getBytes());
        }
        
        // 关闭连接
        channel.close();
        connection.close();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  1. 创建消息消费者

创建一个消息消费者,并实现 Consumer 接口,以便异步处理消息:

import com.rabbitmq.client.*;

import java.io.IOException;

public class TestConsumer implements Consumer {
    public static void main(String[] args) throws Exception {
        // 创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");
        
        // 创建连接
        Connection connection = connectionFactory.newConnection();
        
        // 创建通道
        Channel channel = connection.createChannel();
        
        // 创建队列
        channel.queueDeclare("TestQueue", false, false, false, null);
        
        // 创建消费者
        channel.basicConsume("TestQueue", true, new TestConsumer());
        
        // 等待消息
        Thread.sleep(5000);
        
        // 关闭连接
        channel.close();
        connection.close();
    }
    
    @Override
    public void handleConsumeOk(String consumerTag) {
        
    }
    
    @Override
    public void handleCancelOk(String consumerTag) {
        
    }
    
    @Override
    public void handleCancel(String consumerTag) throws IOException {
        
    }
    
    @Override
    public void handleShutdownSignal(String consumerTag, ShutdownSignalException sig) {
        
    }
    
    @Override
    public void handleRecoverOk(String consumerTag) {
        
    }
    
    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
        String message = new String(body, "UTF-8");
        System.out.println("Received message: " + message);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64

三、 Kafka 示例

在 Java 中,可以使用 Kafka 的 Java 客户端实现消息队列的异步处理。下面是一个简单的示例代码,用于说明如何使用 Kafka 实现消息队列异步处理:

  1. 添加 Kafka 依赖

在 pom.xml 文件中添加以下依赖:

<dependency>
    <groupId>org.apache.kafka</groupId>
    <artifactId>kafka-clients</artifactId>
    <version>2.7.0</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  1. 创建消息队列

创建一个名为 “TestTopic” 的消息队列,并配置 Kafka 连接信息:

import org.apache.kafka.clients.producer.*;

import java.util.Properties;

public class TestProducer {
    public static void main(String[] args) throws Exception {
        // 配置 Kafka 连接信息
        Properties properties = new Properties();
        properties.put("bootstrap.servers", "localhost:9092");
        properties.put("acks", "all");
        properties.put("retries", 0);
        properties.put("batch.size", 16384);
        properties.put("linger.ms", 1);
        properties.put("buffer.memory", 33554432);
        properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        properties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        
        // 创建生产者
        Producer<String, String> producer = new KafkaProducer<>(properties);
        
        // 发送消息
        for (int i = 0; i < 10; i++) {
            String message = "Message " + i;
            producer.send(new ProducerRecord<>("TestTopic", message));
        }
        
        // 关闭生产者
        producer.close();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  1. 创建消息消费者

创建一个消息消费者,并实现 Consumer 接口,以便异步处理消息:

import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.TopicPartition;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class TestConsumer {
    public static void main(String[] args) throws Exception {
        // 配置 Kafka 连接信息
        Properties properties = new Properties();
        properties.put("bootstrap.servers", "localhost:9092");
        properties.put("group.id", "TestGroup");
        properties.put("enable.auto.commit", "false");
        properties.put("auto.offset.reset", "earliest");
        properties.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        properties.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        
        // 创建消费者
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties);
        consumer.subscribe(Arrays.asList("TestTopic"));
        
        // 消费消息
        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(100);
            for (ConsumerRecord<String, String> record : records) {
                System.out.println("Received message: " + record.value());
                
                // 手动提交消费位移
                Map<TopicPartition, OffsetAndMetadata> offsets = new HashMap<>();
                offsets.put(new TopicPartition(record.topic(), record.partition()), new OffsetAndMetadata(record.offset() + 1));
                consumer.commitSync(offsets);
            }
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号