Wednesday, 30 March 2016

Simple Redis PubSub java example

Reff: http://redis.io/topics/pubsub
dependancies :  redis.clients:jedis:2.7.2

To set notify-keyspace-events 
Command: redis-cli config set notify-keyspace-events KEA

Publisher: RedisPub.java


package com.vijaysy.pubsub;

import redis.clients.jedis.Jedis;

import java.util.Scanner;

/**
 * Created by vijaysy on 30/03/16.
 */
public class RedisPub {
    public static void main(String  args[]){
        Jedis jedis = new Jedis("localhost");
        Scanner scanner = new Scanner(System.in);
        System.out.printf("Enter the channel name:");
        String channel=scanner.nextLine();
        System.out.println("Starting publisher for channel "+ channel);

        while (true){
            System.out.println("Enter the string to Publish:");
            String msg = scanner.nextLine();
            jedis.publish(channel,msg);

        }
    }
}


Subscriber:  
RedisSub.java


package com.vijaysy.pubsub;

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

import java.util.Scanner;

/**
 * Created by vijaysy on 30/03/16.
 */
public class RedisSub {

    public static void main(String args[]) {
        Jedis jedis = new Jedis("localhost");
        Scanner scanner = new Scanner(System.in);
        System.out.printf("Enter the channel name:");
        String channel = scanner.nextLine();
        System.out.println("Starting subscriber for channel " + channel);

        while (true) {
            jedis.subscribe(new JedisPubSub() {
                @Override
                public void onMessage(String channel, String message) {
                    super.onMessage(channel, message);
                    System.out.println("Received message:" + message);
                }

                @Override
                public void onSubscribe(String channel, int subscribedChannels) {
                }

                @Override
                public void onUnsubscribe(String channel, int subscribedChannels) {
                }

                @Override
                public void onPMessage(String pattern, String channel, String message) {
                }

                @Override
                public void onPUnsubscribe(String pattern, int subscribedChannels) {
                }
                
                @Override
                public void onPSubscribe(String pattern, int subscribedChannels) {
                }

            }, channel);
        }
    }
}


No comments:

Post a Comment