redis 实现延迟消息队列

Redis延迟消息队列实现

  • List item

配置参数

1.首先确认liunx中安装了redis
2.修改redis的配置文件
配置键空间通知
在 Redis 配置文件(通常是 redis.conf)中,启用键空间通知配置如下:

conf

notify-keyspace-events Ex

E: 启用 Key Event 通知。
x: 启用过期事件通知。

第二步

  redis:
    localhost: 123.249.16.100
    port: 6379
    database: 7
    password: 
    listen-pattern: __keyevent@7__:expired

这里要注意 数据库要设置7的话 listen-pattern里也要是7
这将使客户端收到 Redis 第 7 个数据库中所有过期键的通知。

赋值
   redisTemplate.opsForValue().set(orderNo,"1",24, TimeUnit.SECONDS);
   正常赋值
配置监听
package com.ruoyi.hospital.manager.redis;

import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

@Component
public class TopicMessageListener implements MessageListener {

    @Override
    public void onMessage(Message message, byte[] pattern) {
        byte[] body = message.getBody();
        byte[] channel = message.getChannel();
        //获取到key
        String expiredKey = new String(body);
        String topic = new String(channel);
        System.out.println(expiredKey);
        System.out.println(topic);

    }
}

package com.ruoyi.hospital.manager.redis;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;

@Configuration
public class MessageListenerConfiguration {

    @Value("${spring.redis.listen-pattern}")
    public String pattern;

    @Bean
    public RedisMessageListenerContainer listenerContainer(RedisConnectionFactory redisConnection){
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnection);
        //  设置监听主题
        Topic topic = new PatternTopic(this.pattern);
        container.addMessageListener(new TopicMessageListener(), topic);
        return container;
    }

}

这样 当过期之后就会onMessage方法里执行了

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值