I am working with Spring Boot and Redis server for my web application. When a client sends a post, a message is sent to Redis on channel "chat". This works well. For recieving messages I created the class RedisMessageSubscriber, which recieves messages from Redis. All clients have subscribed the STOMP Websocket client "topic/test".
My question is: How can I redirect the message I recieved in RedisMessageSubscriber to the client Websocket channel?
My first try below didn't worked, because the controller sent a message from the queue to the client before the message received from Redis.
DwittrController.class (Messages are sent to clients here):
@MessageMapping("/newPost")
@SendTo("/topic/test")
public Message message(ClientMessage message) {
log.debug("a message from client was recieved");
userRepository.sendMessage(message.getMessage());
String redisMessage = RedisMessageSubscriber.messageList.get(0);
RedisMessageSubscriber.messageList.remove(0);
return new Message("New post from " + redisMessage + " is available.");
}
UserRepositoryImpl.class:
public void sendMessage(String message) {
stringRedisTemplate.convertAndSend("chat", message);
}
RedisMessageSubscriber.class:
@Component
public class RedisMessageSubscriber implements MessageListener {
private final Logger log = LoggerFactory.getLogger(this.getClass());
public static List<String> messageList = new ArrayList<String>();
public void onMessage(Message message, byte[] pattern) {
messageList.add(message.toString());
log.debug("Message received: " + message.toString());
}
}
In your RedisMessageSubscriber class you can autowire a SimpMessagingTemplate. Code example is not precise, but you get the idea.
@Component
public class RedisMessageSubscriber implements MessageListener {
private final Logger log = LoggerFactory.getLogger(this.getClass());
public static List<String> messageList = new ArrayList<String>();
@Autowired
SimpMessagingTemplate messagingTemplate;
public void onMessage(Message message, byte[] pattern) {
messageList.add(message.toString());
log.debug("Message received: " + message.toString());
messagingTemplate.convertAndSend( "/topic/test", message);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With