上一篇演示了使用纯redis演示布隆过滤(Bloom Filter)器的使用。以及bitmap的一些jedis api.本篇通过jedis的api进行发布订阅消息的案例演示(上)。

package com.coderman.jedis.clusterdemo;

import org.junit.Test;
import redis.clients.jedis.JedisPubSub;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @Author fanchunshuai
 * @Date 2020/1/3 19
 * @Description:
 * 参考 https://blog.csdn.net/yuan52007298/article/details/99320123
 */
public class SubPubTest extends ClusterTest
{
    private static final String TOPIC = "WEIXIN";


    @Test
    public void testPublish(){
        //单个消息发布方
        Long count = cluster.publish(TOPIC,"您有一条微信技术文章.");
        System.out.println("count = "+count);
    }

    @Test
    public void testSubscribe(){
        //这种方式存在阻塞,redis重启会导致订阅中断,使用下面的线程池方式
        //cluster.subscribe(new WeixinSubscribe(),TOPIC);
        //下面使用第二种方式
        try {
            //单个消息订阅方
            Executors.newSingleThreadScheduledExecutor().
                    scheduleWithFixedDelay(new Thread(()->{
                        System.out.println("恢复订阅........");
                        cluster.subscribe(new MutilSubscribeOne(),TOPIC);

                    },"jedis subscribe thread"),0L,1000L, TimeUnit.MILLISECONDS).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

}

/**
 * 自定义订阅类
 */
class WeixinSubscribe extends JedisPubSub{
    @Override
    public void onMessage(String channel, String message) {
        System.out.println("channel = "+channel+",message = "+message);

    }

    @Override
    public void onSubscribe(String channel, int subscribedChannels) {
        System.out.println("channel = "+channel+",subscribedChannels = "+subscribedChannels);
    }
}
Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐