spring redis 消息队列

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值