How to use the "message queue client" framework in the Java class library to pass the message
The message queue is a lightweight communication mode that transmits messages between applications.The Java class library provides many different "message queue clients" framework to simplify the processing and receiving process of messages.This article will introduce how to use the message queue client framework in the Java library to pass messages, and provide some example code to help readers understand.
First, we need to introduce the Java library of the message queue client framework.According to different frameworks used, you can import the required dependencies by adding corresponding jar files in the Java project or using the construction tool (such as Maven or Gradle).
The following uses Apache Kafka and Rabbitmq as an example to introduce how to use the message queue client framework for message transmission.
1. Use Apache Kafka to transfer messages
Apache Kafka is a distributed stream processing platform that is widely used to build real -time data pipelines and streaming applications.The following is a sample code using Kafka:
import org.apache.kafka.clients.producer.*;
import org.apache.kafka.clients.consumer.*;
// Create a producer
Properties producerProps = new Properties();
producerProps.put("bootstrap.servers", "localhost:9092");
producerProps.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
producerProps.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
Producer<String, String> producer = new KafkaProducer<>(producerProps);
// Send a message
String topic = "my-topic";
String key = "key";
String value = "Hello, Kafka!";
producer.send(new ProducerRecord<>(topic, key, value), new Callback() {
public void onCompletion(RecordMetadata metadata, Exception exception) {
if (exception != null) {
exception.printStackTrace();
} else {
System.out.println ("Message is successful, partition:" + metadata.partition () + ", offset:" + metadata.offset ());
}
}
});
// Create consumers
Properties consumerProps = new Properties();
consumerProps.put("bootstrap.servers", "localhost:9092");
consumerProps.put("group.id", "my-group");
consumerProps.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
consumerProps.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
Consumer<String, String> consumer = new KafkaConsumer<>(consumerProps);
// Subscribe to topic
consumer.subscribe(Collections.singletonList(topic));
// Receive messages
while (true) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
for (ConsumerRecord<String, String> record : records) {
System.out.println ("Receive messages: key =" + record.key () + ", value =" + record.value ());
}
}
2. Use Rabbitmq to transfer messages
Rabbitmq is an open source message queue system that implements AMQP (senior message queue protocol) standard.The following is an example code using Rabbitmq:
import com.rabbitmq.client.*;
// Create connections and channels
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
// Create queue and switch
String queueName = "my-queue";
channel.queueDeclare(queueName, false, false, false, null);
String exchangeName = "my-exchange";
channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT, false);
String routingKey = "my-routing-key";
channel.queueBind(queueName, exchangeName, routingKey);
// Send a message
String message = "Hello, RabbitMQ!";
channel.basicPublish(exchangeName, routingKey, null, message.getBytes());
System.out.println ("Message successful:" + Message);
// Create consumers
channel.basicConsume(queueName, true, new DeliverCallback() {
public void handle(String consumerTag, Delivery delivery) throws IOException {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println ("Receive messages:" + message);
}
}, new CancelCallback() {
public void handle(String consumerTag) throws IOException {
System.out.println ("Cancer:" + consumertag);
}
});
// Turn off the connection
channel.close();
connection.close();
In the above code, we used the `kafkaproducer` and` kafkaconsumers to create producers and consumers, and send and receive messages through the specified theme.For Rabbitmq, we use the `Connection`, Channel` and` Exchange` to create a connection and switch, and send messages with the `BasicPublish`, and register a callback function through the` BasicConsume`.
In summary, the use of the "Message Client" framework in the Java library for messages to transmit messages involving creators and consumers, setting up related framework specific attributes, sending and receiving messages.Developers can choose the appropriate message queue client framework according to their needs, and write code writing according to the API provided by the framework.Through the message queue, applications can achieve efficient asynchronous communication, improve the concurrency and scalability of the system.