yanderong
2026-06-10 0a50085d6ef51274c28d3915446af6d9ddd91cd2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.stylefeng.guns.modular.system.util.redisqueue;
 
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
 
import java.util.Collections;
import java.util.List;
 
@Component
public class RedisFifoQueue {
 
    private final Jedis jedis;
    private final String queueKey;
 
    private String host="127.0.0.1";
 
    private int port=10644;
 
    private String password="JiXiChuXing2026!Redis@";
 
    private String queueKeyFromConfig ="my_queue";
 
    public RedisFifoQueue() {
        this.jedis = new Jedis(host, port);
        if (password != null && !password.isEmpty()) {
            this.jedis.auth(password);
        }
        this.queueKey = queueKeyFromConfig;
    }
    public RedisFifoQueue(String host, int port, String queueKey) {
        this.jedis = new Jedis(host, port);
        this.queueKey = queueKey;
    }
 
    // 入队:添加元素到队列末尾
    public void enqueue(String item) {
        jedis.rpush(queueKey, item);
        System.out.println("入队: " + item);
    }
 
    // 出队:从队列头部取出元素(阻塞可选)
    public String dequeue() {
        String item = jedis.lpop(queueKey);
        if (item != null) {
            System.out.println("出队: " + item);
        } else {
            System.out.println("队列为空");
        }
        return item;
    }
    public void removeOrderById(String orderId) {
 
        jedis.lrem(queueKey, 0, orderId);
    }
    public RedisFifoQueue(String host, int port, String password, String queueKey) {
        this.jedis = new Jedis(host, port);
        this.jedis.auth(password);  // 添加密码认证
        this.queueKey = queueKey;
    }
    /**
     * 获取队列中所有元素(按 FIFO 顺序)
     * @return 队列中的所有元素列表
     */
    public List<String> getAllItems() {
        Long size = jedis.llen(queueKey);
        if (size == 0) {
            return Collections.emptyList();
        }
        // LRANGE key start stop,0 表示第一个元素,-1 表示最后一个元素
        return jedis.lrange(queueKey, 0, -1);
    }
    /**
     * 清空整个队列
     */
    public void clearQueue() {
        jedis.del(queueKey);
        System.out.println("队列已清空");
    }
 
    // 查看队列大小
    public long size() {
        return jedis.llen(queueKey);
    }
 
    // 关闭连接
    public void close() {
        jedis.close();
    }
}