问题
How can I schedule a "push" of specified data every few seconds using a Spring Boot WebSocket controller? I currently have the following code:
@Controller
public class ServiceWebSocketController {
@Autowired
private ServiceService serviceService;
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;
// This method works great, but a response is only sent to the client once.
@SubscribeMapping("/service/{serviceId}")
public ServiceDTO subscribed(@DestinationVariable("serviceId") final Long serviceId) throws SQLException {
return serviceService.getService(serviceId).orElseThrow(() -> new ResourceNotFoundException("Service", "id", serviceId));
}
// This does not work.
@Scheduled(fixedDelay = 2000)
public void service(@DestinationVariable("serviceId") final Long serviceId) throws SQLException {
simpMessagingTemplate.convertAndSend("/topic/service/", serviceService.getService(serviceId));
}
}
Unfortunately, the code above does not work due to an exception thrown at runtime (java.lang.IllegalStateException: Encountered invalid @Scheduled method 'service': Only no-arg methods may be annotated with @Scheduled
).
Unlike the @SubscribeMapping
annotation, I cannot pass a destination variable (e.g., serviceId
) from the client which subscribes to the method to know to which "service
" I must subscribe to.
This method works perfectly well when used as follows:
@Scheduled(fixedDelay = 2000)
public void services() throws SQLException {
simpMessagingTemplate.convertAndSend("/topic/services", serviceService.getAllServices());
}
In the latter case, the method parameters remain empty and a list of all services is sent to the client.
How can a client subscribe to a specific publication (.e.g., "/topic/services/{serviceId}
") and then receive the same data periodically until the client eventually unsubscribes?
来源:https://stackoverflow.com/questions/54942000/how-can-i-schedule-a-push-of-client-specified-data-every-few-seconds-using-a-s