(二)redis发布订阅---取消订阅

接上一讲:

一、取消订阅是使用监听器类RedisMsgPubSubListener中的unsubscribe方法,首先我们创建一个线程类:

 

package redis.v1.client.thread;

import redis.clients.jedis.Jedis;
import redis.v1.client.common.PubSubCommons;
import redis.v1.client.server.RedisClient;

public class UnsubscribeRunable implements Runnable{

	@Override
	public void run() {
		int i = 1;
		while(true) {
			try {
				Thread.sleep(1000*i);
				System.out.println("休眠第"+i+"秒");
				i = i*2;
				if(i/10 == 0) {
					PubSubCommons.listener.unsubscribe("redisChat1");
					PubSubCommons.listener.unsubscribe("redisChat");
					PubSubCommons.listener.unsubscribe("redisChat2");
				}
//				PubSubCommons.listener.onPong("redisChat?");
//				Jedis jedis = RedisClient.getJedis();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

}

二、在订阅通道类中加入如下代码:

 

 

new Thread(new UnsubscribeRunable()).start();

 

package redis.v1.client;

import java.util.Iterator;
import java.util.Set;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;
import redis.v1.client.common.PubSubCommons;
import redis.v1.client.listener.RedisMsgPubSubListener;
import redis.v1.client.server.RedisClient;
import redis.v1.client.thread.UnsubscribeRunable;

public class RedisSubscribe {

	public static void main(String[] args) {
		Jedis jedis = RedisClient.getJedis();
		System.out.println("订阅服务器运行状态:"+jedis.ping());
		
		new Thread(new UnsubscribeRunable()).start();
		
		String[] str = {"redisChat","redisChat1","redisChat2"};
		jedis.subscribe(PubSubCommons.listener, str);
//		jedis.close();
	}
}


运行结果如下:

 

 

订阅服务器运行状态:PONG
onSubscribe---redisChat---1
onSubscribe---redisChat1---2
onSubscribe---redisChat2---3
休眠第1秒
onUnsubscribe---redisChat1---2
onUnsubscribe---redisChat---1
onUnsubscribe---redisChat2---0
休眠第2秒

 

 

 

 

 


 

 

你可能感兴趣的:(【MongoDB/Redis】)