0
votes

According to the documentation for RedisMessageListnerContainer -

public void addMessageListener(MessageListener listener, Topic topic):

Adds a message listener to the (potentially running) container. If the container is running, the listener starts receiving (matching) messages as soon as possible.

The quote above seems to indicate that there is no real way of knowing when the listener is ready - or whether the subscription at all succeeds.

So, given that I publish and subscribe to a channel - how long should I wait until I can start publishing? In my tests, simply executing

container.addMessageListener(listener, topic);
for(int i = 0; i < 10; i++) {
   template.publish(topic, content);
}

means that I don't receive the first 3-5 messages that I myself have published.

How do I get around this without resorting to Thread.sleep()? Is it possible to get notified about connection failure/success etc?

1

1 Answers

0
votes

The problem I had that messages was lost when subscribing to a topic and then immediately publishing to it disappeared when I set up the MessageListener bean to listen to a dummy topic during bean initialization:

@Bean
ChannelTopic channelTopic() {
    return new ChannelTopic(UUID.randomUUID().toString());
}

@Bean
RedisMessageListenerContainer redisContainer(JedisConnectionFactory jedisConnectionFactory) {
    final RedisMessageListenerContainer redisContainer = new MessageListenerContainerAdapter();
    redisContainer.setConnectionFactory(jedisConnectionFactory);
    redisContainer.addMessageListener(messageListenerAdapter(messageReceiveQueue()), channelTopic());
    return redisContainer;
}

I can now subscribe to a new topic and publish to it immediately.