## Xây dựng Hệ thống Hàng đợi

Bằng cách sử dụng các lệnh lpop và lpush của cấu trúc dữ liệu list, một hàng đợi tin nhắn (message queue) có thể dễ dàng được triển khai trong Redis. Cách tiếp cận này cho phép việc ghi và tiêu thụ hàng đợi diễn ra một cách hiệu quả. Vì hàng đợi tin nhắn độc lập với máy chủ trò chơi, nhiều máy chủ trò chơi có thể trao đổi dữ liệu và gửi sự kiện thông qua nó. Ngoài ra, một hệ thống hàng đợi ưu tiên có thể được xây dựng bằng cách sử dụng sorted set, cho phép xử lý tin nhắn phức tạp hơn và ưu tiên các sự kiện.

``` java
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();
    }
}
```

Kết quả đầu ra:

```
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
```