Asynchronous Messaging In Java with Examples
There are several ways to implement asynchronous messaging in Java, including using the Java Message Service (JMS), messaging libraries like Apache Kafka or RabbitMQ, and the new CompletableFuture API introduced in Java 8.
1. Java Message Service (JMS)
ConnectionFactory connectionFactory
= new ActiveMQConnectionFactory("tcp://localhost:61616");
Connection connection = connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue("myQueue");
MessageProducer producer = session.createProducer(destination);
TextMessage message = session.createTextMessage("Hello, world!");
producer.send(message);
connection.close();
And here's an example of how to receive a message asynchronously using JMS:
ConnectionFactory connectionFactory
= new ActiveMQConnectionFactory("tcp://localhost:61616");
Connection connection = connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue("myQueue");
MessageConsumer consumer = session.createConsumer(destination);
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
try {
System.out.println("Received message: " + textMessage.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
}
});
connection.close
2. Apache Kafka
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("acks", "all");
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
Producer<String, String> producer = new KafkaProducer<>(props);
producer.send(new ProducerRecord<>("myTopic", "Hello, world!"));
producer.close();
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("group.id", "myGroup");
props.put("enable.auto.commit", "true");
props.put("auto.commit.interval.ms", "1000");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer",
"org.apache.kafka.common.serialization.StringDeserializer");
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Collections.singletonList("myTopic"));
while (true) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
for (ConsumerRecord<String, String> record : records) {
System.out.printf("offset = %d, key = %s, value = %s%n",
record.offset(), record.key(), record.value());
}
}
consumer.close();
3. RabbitMQ
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("myQueue", false, false, false, null);
channel.basicPublish
onnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("myQueue", false, false, false, null);
Consumer consumer = new DefaultConsumer(channel) {
@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);
}
};
channel.basicConsume("myQueue", true, consumer);
connection.close();
4. CompletableFuture API
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// send message asynchronously
return "Hello, world!";
});
future.thenAcceptAsync(message -> {
// receive message asynchronously
System.out.println("Received message: " + message);
});
Conclusion
Other Java Microservices articles and tutorials you may like:
- 10 Best Courses to learn Spring in-depth
- 15 Microservice Interview Question and Answers
- How to create Microservice with Java and Spring
- 5 Courses to Learn Big Data and Apache Spark
- 5 Books to learn Microservice in Java
- 5 Best Courses to learn Spring MVC for Beginners
- 5 Online Courses to learn Core Java for Free
- 10 courses for Programming/Coding Job Interviews
- 5 Essential Skills to Crack Coding Interviews
- 10 Advanced Spring Boot Courses for Java Programmers
- 5 Free Spring Framework Courses for Java Developers
- 10 Free Courses to learn Spring for Beginners
- 5 Essential Frameworks Every Java developer should learn
- 10 Free Spring Boot Tutorials and Courses for Java Devs
- Top 5 Courses to learn Microservice with Spring Boot
- Top 5 Java design patterns courses for experienced Java devs
Thanks for reading this article so far. If you like this article about Asynchronous messaging in Java and Microservice architecture and how to use it then please share them with your friends and colleagues. If you have any questions, feedback, or other fee courses to add to this list, please feel free to suggest.
No comments:
Post a Comment
Feel free to comment, ask questions if you have any doubt.