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.RestGreetingService;
13 @Service("restGreetingService")
14 public class RestGreetingServiceImpl
15 implements RestGreetingService, ApplicationListener<BrokerAvailabilityEvent> {
16 private final SimpMessagingTemplate template;
18 private volatile boolean isBrokerAvailable = true;
21 public RestGreetingServiceImpl(SimpMessagingTemplate template) {
22 this.template = template;
26 public void doGreetings(String greeting) {
27 String text = "[" + LocalDateTime.now() + "]:" + greeting;
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);
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();