Jedis实现发布(Publish) 订阅(Subscribe)

package com.zhuyang.redis.mq;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
 * get  Jedis 
 * @author zhuyang
 *
 */
public class Utils {
	public static JedisPoolConfig getJedisPoolConfig() {
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxIdle(0);
		config.setMaxWaitMillis(1000);
		return config;
	}

	public static JedisPool getJedisPool() {
		JedisPool pool = new JedisPool(getJedisPoolConfig(), "localhost");
		return pool;
	}

	public static Jedis getJedis() {
		Jedis jedis = getJedisPool().getResource();
		return jedis;

	}

}

package com.zhuyang.redis.mq;

import redis.clients.jedis.Jedis;

public class Publisher {
	public static void main(String[] args) {
		Jedis jedis = Utils.getJedis();
		jedis.publish("channel1", "message from channel1");
		jedis.publish("channel2", "message from channel2");
	}
}

package com.zhuyang.redis.mq;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;

public class Consumer extends JedisPubSub {
	public void onPMessage(String pattern, String channel, String message) {
		System.out.println("onPMessage()," + pattern + "=" + channel + "="
				+ message);
	}

	public void onMessage(String channel, String message) {
		System.out.println("onMessage()," + channel + "=" + message);
	}

	public static void main(String[] args) {
		Consumer c = new Consumer();
		Jedis jedis = Utils.getJedis();
		//jedis.subscribe(c, "channel1");//handle by onMessage()
		jedis.psubscribe(c, new String[]{"chan*"}); // handle by onPMessage()
	}
}




你可能感兴趣的:(nosql)