As i am using below code for Publisher and Subscriber in Redis. I am using redis server version 3.2.6 and I am connecting from redis java client jedis of version 2.9.0 using below maven dependancy,
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
Here is my code,
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import redis.clients.jedis.Jedis;
//import redis.clients.jedis.BinaryJedisPubSub;
import redis.clients.jedis.JedisPubSub;
public class JavaProject extends JedisPubSub{
public static void main(String[] args) throws IOException, InterruptedException {
Jedis jedis = new Jedis("192.168.0.20");
try {
jedis.connect();
System.out.println("Connected");
String subChannel = "192168026*";
JavaProject javaProject=new JavaProject();
jedis.subscribe(javaProject,subChannel);
System.out.println("Subscribed to topic");
jedis.publish(subChannel, "Hi".getBytes());
System.out.println("Published to topics");
}
catch(Exception jce){
jce.printStackTrace();
}
finally {
jedis.close();
}
System.out.println("Program Completed");
while(true){
}
}
@Override
public void onUnsubscribe(String arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onSubscribe(String arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onPUnsubscribe(String arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onPSubscribe(String arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onPMessage(String arg0, String arg1, String arg2) {
// TODO Auto-generated method stub
}
@Override
public void onMessage(String channel, String message) {
System.out.println(message);
}
}
when i execute above code, I get below output Connected
But it hangs on subscribe() method , execution does not move further to next line So what is wrong in this code?
Thanks
You need a dedicated Redis connection for the subscription, and also probably a dedicated thread.
Once a subscribe operation has been applied, no other command can be sent to the Redis server on this connection, except subscription related commands (SUBSCRIBE, PSUBSCRIBE, UNSUBSCRIBE, PUNSUBSCRIBE, PING and QUIT).
With Jedis, the subscribe operation is blocking, so it should run in a separate thread. Note that the callbacks triggered by Jedis will run in that thread as well.