Redis 订阅消息

public class TestRedisPubSub {

	public static void main(String[] args)
	{
		JedisPool jedisPool = new JedisPool(new JedisPoolConfig(), "127.0.0.1", 6379);

		// consumer
		new Thread(new Runnable() {

			public void run() {
				Jedis jedis = jedisPool.getResource();
				jedis.subscribe(new JedisPubSub() {

					  @Override
					    public void onMessage(String channel, String message) {       //收到消息会调用
					        System.out.println(String.format("收到消息成功:  %s", message));
					    }

					    @Override
					    public void onSubscribe(String channel, int subscribedChannels) {    //订阅频道会调用
					        System.out.println(String.format("订阅频道成功! channel: %s, subscribedChannels %d", channel, subscribedChannels));
					    }

					    @Override
					    public void onUnsubscribe(String channel, int subscribedChannels) {   //取消订阅会调用
					        System.out.println(String.format("取消订阅频道! channel: %s, subscribedChannels: %d", channel, subscribedChannels));
					    }

				}, "pangugle_sms");
			}
		}).start();


		// send message
		Jedis sendRedis = jedisPool.getResource();

		boolean rs = true;
		int index = 0;
		while(rs)
		{
			String msg = "msgid = " + index ++;
			sendRedis.publish("pangugle_sms", msg);
			ThreadUtils.sleep(1000);
		}

		jedisPool.close();
	}

}