import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
@Service
public class RedisQueueService {
private static final String QUEUE_KEY = "myQueue";
@Autowired
private RedisTemplate<String, String> redisTemplate;
/**
* 生产者:向队列左侧推入消息
*/
public void pushMessage(String message) {
redisTemplate.opsForList().leftPush(QUEUE_KEY, message);
}
/**
* 消费者:弹出队列右侧消息(非阻塞)
* @return 消息,若队列为空返回null
*/
public String popMessage() {
return redisTemplate.opsForList().rightPop(QUEUE_KEY);
}
/**
* 消费者:阻塞弹出队列右侧消息,等待时间单位秒
* @param timeout 超时时间,0表示无限等待
* @return 消息,超时返回null
*/
public String blockingPopMessage(long timeout) {
// 返回 List<Object>,第一个是key,第二个是value
java.util.List<String> result = redisTemplate.opsForList().rightPop(QUEUE_KEY, timeout);
return result == null || result.isEmpty() ? null : result.get(1);
}
/**
* 查询队列长度
*/
public Long getQueueLength() {
return redisTemplate.opsForList().size(QUEUE_KEY);
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
@Service
public class RedisQueueListener {
private static final String QUEUE_KEY = "myQueue";
@Autowired
private RedisTemplate<String, String> redisTemplate;
/**
* 启动监听线程,持续阻塞监听队列
*/
@PostConstruct
public void startListener() {
Thread thread = new Thread(() -> {
while (true) {
try {
// 阻塞弹出消息,超时时间为0,表示无限等待
String message = redisTemplate.opsForList().rightPop(QUEUE_KEY, 0);
if (message != null) {
// 消息处理逻辑
System.out.println("收到消息:" + message);
// 这里可以调用业务处理方法
}
} catch (Exception e) {
e.printStackTrace();
// 发生异常时休眠几秒,防止死循环
try {
Thread.sleep(3000);
} catch (InterruptedException ignored) {}
}
}
});
thread.setDaemon(true); // 守护线程,随应用关闭
thread.start();
}
}