Building Queue System
By using the lpop and lpush commands of the list data structure, a message queue can be easily implemented in Redis. This approach allows for efficient queue writing and consumption. Since the message queue is independent of the game server, multiple game servers can exchange data and send events through it. Additionally, a priority queue system can be constructed using a sorted set, enabling more complex message handling and prioritization of events.
import redis.clients.jedis.Jedis;
class ProducerThread extends Thread {
private Jedis jedis;
private int port;
private String host,key;
ProducerThread(String host, int port, String key) {
super(host);
this.key = key;
this.port = port;
jedis = new Jedis(host, port);
}
protected void finalize( ){
jedis.close();
}
public void run() {
//System.out.println("ProducerThread is running...");
for(int i = 0; i < 10; i++) {
jedis.lpush(key, "job"+ Integer.toString(i));
System.out.println("ProducerThread push job"+ Integer.toString(i));
}
}
}
class ConsumerThread extends Thread {
private Jedis jedis;
private int port;
private String host,key;
ConsumerThread(String host, int port, String key) {
super(host);
this.key = key;
this.port = port;
jedis = new Jedis(host, port);
}
protected void finalize( ) {
jedis.close();
}
public void run() {
//Building queue system
//System.out.println("ConsumerThread is running...");
for(int i = 0; i < 10; i++) {
System.out.println("ConsumerThread pop "+ jedis.lpop(key));
}
}
}
public class QueueSystem {
public static void main(String[] args) {
String host = "127.0.0.1";
int port = 10011;
String key = "jobs";
ProducerThread pT = new ProducerThread(host,port,key);
ConsumerThread cT = new ConsumerThread(host,port,key);
pT.start();
cT.start();
}
}
Output:
ConsumerThread pop null
ProducerThread push job0
ConsumerThread pop job0
ProducerThread push job1
ConsumerThread pop job1
ProducerThread push job2
ConsumerThread pop job2
ProducerThread push job3
ConsumerThread pop job3
ProducerThread push job4
ConsumerThread pop job4
ProducerThread push job5
ConsumerThread pop job5
ProducerThread push job6
ConsumerThread pop job6
ProducerThread push job7
ConsumerThread pop job7
ProducerThread push job8
ConsumerThread pop job8
ProducerThread push job9