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");
    }
}
监测键的过期时间: 监测键值
__keyevent@0__:expired

猜你喜欢

转载自blog.csdn.net/qq_27986007/article/details/80890207