注意:本博客前置条件,熟悉redis并且知道如何启动redis服务器
<?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.leftso.redis</groupId>
<artifactId>message-queue</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>REDDIS - ${project.artifactId}</name>
<url>http://leftso.com</url>
<dependencies>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.2</version>
</dependency>
</dependencies>
</project>
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");
}
}
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));
}
}
}
$title(console)
Waiting for a message in the queue
$title(console)
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
https://www.leftso.com/article/614.html