redis 发布与订阅 :java,以及键过期时间监控

package com.example.demo.RedisPubSubAndListener;

import redis.clients.jedis.JedisPubSub;
public class PubSubScriber  extends JedisPubSub {
//订阅消息的处理类
    @Override
    public void onMessage(String channel, String message) {       //收到消息会调用
        System.out.println(String.format("receive redis published message, channel %s, message %s", channel, message));
    }
    @Override
    public void onSubscribe(String channel, int subscribedChannels) {    //订阅了频道会调用
        System.out.println(String.format("subscribe redis channel success, channel %s, subscribedChannels %d",
                channel, subscribedChannels));
    }
    @Override
    public void onUnsubscribe(String channel, int subscribedChannels) {   //取消订阅 会调用
        System.out.println(String.format("unsubscribe redis channel, channel %s, subscribedChannels %d",
                channel, subscribedChannels));

    }
}
 
package com.example.demo.RedisPubSubAndListener;


import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
//发布消息
@RestController
@RequestMapping("/redis")
public class PubRedisController {
    @Resource
    private StringRedisTemplate  strRedisTemplate;


    @RequestMapping("/pub")
    public String pubMessage() {
        strRedisTemplate.convertAndSend("pub_test","heheheh");
        System.out.println("pub test");
        return "success";
    }
}

 

 

 

 

package com.example.demo.RedisPubSubAndListener;

import redis.clients.jedis.Jedis;
public class SubThread extends Thread{

    private Jedis jedis = new Jedis("10.7.8.3",6379);
    {
        jedis.auth("redisqa");
    }
    @Override
    public void run() {
     //订阅主题
        jedis.subscribe(new PubSubScriber(),"channel");
    }
}

在redis.conf 添加配置:notify-keyspace-events "Ex" //过期时间监听生效

监测键的过期时间: 监测键值

__keyevent@0__:expired
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值