Redis发布订阅例子

做了个简单的例子这里记录一下

 

订阅1

public class RedisClientOne {
    /**
     * 订阅消息
     * @param args
     */
    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        jedis.auth("123456");
        JedisPubSub jedisPubSub = new JedisPubSub() {
            @Override
            public void onMessage(String channel, String message) {
                super.onMessage(channel, message);
                System.out.println(message);
            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                jedis.subscribe(jedisPubSub, "channel");
            }
        }).start();
        //JedisPubSubMap.put("channel",jedisPubSub);

    }

}

订阅2

public class RedisClientTwo {
    /**
     * 订阅消息
     * @param args
     */
    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        jedis.auth("123456");
        JedisPubSub  jedisPubSub = new JedisPubSub() {
            @Override
            public void onMessage(String channel, String message) {
                super.onMessage(channel, message);
                System.out.println(message);
            }
        };

        new Thread(new Runnable() {
            @Override
            public void run() {
                jedis.subscribe(jedisPubSub, "channel");
            }
        }).start();

        //JedisPubSubMap.put("two",jedisPubSub);

    }

}

发布端

   /**
     * 发布消息,渠道和消息值
     * @param args
     */
    public static void main(String[] args) {

        Jedis jedis = new Jedis("127.0.0.1", 6379);
        jedis.auth("123456");

        for (int i = 0; i < 10; i++) {
            String a ="数字"+i;
            jedis.publish("channel", a);
        }
    }

 

 

你可能感兴趣的:(redis)