Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring data Redis Pub/Sub and Websockets: recieving messages

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());
    }

}
like image 806
Alina Ja Avatar asked Oct 17 '22 23:10

Alina Ja


1 Answers

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);
    }

}
like image 106
Pavel Gyurov Avatar answered Oct 20 '22 17:10

Pavel Gyurov