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