Redis中的发布订阅

http://www.cnblogs.com/mushroom/p/4470006.html#one

package com.demo.redis;

import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

import org.apache.commons.lang3.StringUtils;

import com.support.RedisTool;

import redis.clients.jedis.JedisPubSub;

public class Test {

	public static void main(String[] args) {
		new Test().test();
	}

	public void test1() {
		String loginip = "127.0.0.1";
		long timestamp = System.currentTimeMillis() / 1000;
		Integer logType = 2;
		List<?> event = Arrays.asList("userId", loginip, timestamp, logType);

		System.err.println(event);
	}

	static String topic = "test";

	public void test() {

		JedisPubSubListener listener = new JedisPubSubListener();
		Thread th = new Thread(new Receive(topic, listener));
		th.setName("abc");
		th.start();
		input();
	}

	public void input() {
		Scanner scanner = new Scanner(System.in);
		while (true) {
			String str = scanner.nextLine();
			if (StringUtils.equals(str, "quit")) {
				break;
			}

			RedisTool.keep().getJedis().publish(topic, str);
		}

		scanner.close();
		RedisTool.keep().getJedis().shutdown();
	}
}

class Receive implements Runnable {

	String topic;
	JedisPubSubListener listener;

	public Receive() {

	}

	public Receive(String topic, JedisPubSubListener listener) {
		this.topic = topic;
		this.listener = listener;
	}

	@Override
	public void run() {
		RedisTool.keep().getJedis().subscribe(listener, topic);
	}

}

class JedisPubSubListener extends JedisPubSub {

	@Override
	public void onMessage(String channel, String message) {
		String name = Thread.currentThread().getName();
		System.err.println(name + ": " + message);
	}
}

猜你喜欢

转载自jis117.iteye.com/blog/2286093