Simple Redis Message Queue
In this tutorial we will build a redis message queue. Redis can be used as a Message Queue. Messages will be queued in a list by key-value. Producers add messages into the end of the list using the RPUSH
command and consumers can read these messages in the beginning of the list with the BLPOP
command using FIFO processing. Continue reading for more information.
Maven Dependency
We need a java client which can connect to the redis server. Say hello to Jedis.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.memorynotfound.reddis</groupId>
<artifactId>message-queue</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>REDDIS - ${project.artifactId}</name>
<url>https://memorynotfound.com</url>
<dependencies>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.2</version>
</dependency>
</dependencies>
</project>
Redis Message Queue Producer
Lets start by publishing messages to the mq-key
queue using the rpush()
method. Which will add a message to the end of the list.
package com.memorynotfound;
import redis.clients.jedis.Jedis;
public class MessageProducer {
public static void main(String... args) {
Jedis jedis = new Jedis("localhost");
jedis.rpush("mq-key", "first message");
jedis.rpush("mq-key", "second message");
jedis.rpush("mq-key", "third message");
}
}
Redis Message Queue Consumer
We can consume messages by using the lpop()
or blpop()
methods. We will use the blocking lpop method which as the name indicates will block the thread until a new message comes along. We can provide a timeout indicating how long the request will wait for a message. We provide 0 which means that there will be no timeout.
package com.memorynotfound;
import redis.clients.jedis.Jedis;
import java.util.List;
public class MessageConsumer {
private static final int TIMEOUT = 0;
public static void main(String... args ) {
Jedis jedis = new Jedis("localhost");
while(true){
System.out.println("Waiting for a message in the queue");
List<String> messages = jedis.blpop(TIMEOUT, "mq-key");
System.out.println("received message with key:" + messages.get(0) + " with value:" + messages.get(1));
}
}
}
Starting Message Consumer
First lets start the message consumer which will listen to messages with mq-key
key value.
Waiting for a message in the queue
Starting Message Producer
Waiting for a message in the queue
received message with key:mq-key with value:first message
Waiting for a message in the queue
received message with key:mq-key with value:second message
Waiting for a message in the queue
received message with key:mq-key with value:third message
Waiting for a message in the queue