e0d63e29a38b86dbf4b32f75f8cfa6441e646c24
[JavaForFun] /
1 package de.spring.stomp.services.impl;
2
3 import java.time.LocalDateTime;
4
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;
10
11 import de.spring.stomp.services.UserTradeService;
12
13 @Service("userTradeService")
14 public class UserTradeServiceImpl
15                 implements UserTradeService, ApplicationListener<BrokerAvailabilityEvent> {
16         private final SimpMessagingTemplate template;
17         
18         private volatile boolean isBrokerAvailable = true;
19
20     @Autowired
21     public UserTradeServiceImpl(SimpMessagingTemplate template) {
22         this.template = template;
23     }
24     
25         @Override
26         public void doTrade(String user) {
27                 String text = "[" + LocalDateTime.now() + "]:" + user;
28                 
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);
32                 }
33         }
34
35         @Override
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();
42         }
43
44 }