I just created an instance of Jedis (Redis for Java) and connected to my redis server.
My backend should be able to run more than once so for example the user-cache must be invalidated if a user becomes updated.
I want to send with redis a message to all servers - which subscribed for example the user_update channel - to clear the cache after incoming message on this channel.
I created a new thread with new Thread(() -> this.jedis.subscribe(this, "user_update")).start();
and listened to the new channel. So a new thread is required otherwise my programm is stuck if that line is called.
I extended my own class from the JedisPubSub and implemented the following method:
@Override
public void onMessage(String channel, String message) {
System.out.println(channel + " -> " + message);
}
Now if I use the this.jedis.publish(channel, message);
method an error will be thrown:
redis.clients.jedis.exceptions.JedisDataException: ERR Can't execute 'publish': only (P|S)SUBSCRIBE / (P|S)UNSUBSCRIBE / PING / QUIT / RESET are allowed in this context
I guess it's because I listened on the server instance to the message. But why does that happen? Any ideas?
How can I only listen to other servers?
You are using same Jedis object for both subscribe and publish operations. Use separate Jedis objects for these purposes.