b518e76e70dd23e4e44fddb90014e049a76d2605
[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.RestGreetingService;
12
13 @Service("restGreetingService")
14 public class RestGreetingServiceImpl
15                 implements RestGreetingService, ApplicationListener<BrokerAvailabilityEvent> {
16         private final SimpMessagingTemplate template;
17         
18         private volatile boolean isBrokerAvailable = true;
19
20     @Autowired
21     public RestGreetingServiceImpl(SimpMessagingTemplate template) {
22         this.template = template;
23     }
24
25         @Override
26         public void doGreetings(String greeting) {
27                 String text = "[" + LocalDateTime.now() + "]:" + greeting;
28                 
29                 if (isBrokerAvailable) {
30                         // STOMP clients subscribed to /topic/greeting will receive the data sent by the convertAndSend method.
31                         template.convertAndSend("/topic/greeting", 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 }