1 package de.spring.stomp.services.impl;
3 import java.time.LocalDateTime;
5 import org.springframework.beans.factory.annotation.Autowired;
6 import org.springframework.context.ApplicationListener;
7 import org.springframework.messaging.simp.SimpMessagingTemplate;
8 import org.springframework.messaging.simp.broker.BrokerAvailabilityEvent;
9 import org.springframework.stereotype.Service;
11 import de.spring.stomp.services.UserTradeService;
13 @Service("userTradeService")
14 public class UserTradeServiceImpl
15 implements UserTradeService, ApplicationListener<BrokerAvailabilityEvent> {
16 private final SimpMessagingTemplate template;
18 private volatile boolean isBrokerAvailable = true;
21 public UserTradeServiceImpl(SimpMessagingTemplate template) {
22 this.template = template;
26 public void doTrade(String user) {
27 String text = "[" + LocalDateTime.now() + "]:" + user;
29 if (isBrokerAvailable) {
30 // STOMP clients subscribed to /topic/position-updates will receive the data sent by the convertAndSend method.
31 template.convertAndSendToUser(user, "/topic/position-updates", text);
36 public void onApplicationEvent(BrokerAvailabilityEvent event) {
37 // Components using the SimpMessagingTemplate should subscribe to this event
38 // and avoid sending messages at times when the broker is not available.
39 // In any case they should be prepared to handle MessageDeliveryException
40 // when sending a message.
41 isBrokerAvailable = event.isBrokerAvailable();