How can I schedule a “push” of client-specified data every few seconds using a Spring Boot WebSocket controller?

依然范特西╮ 提交于 2020-01-01 19:58:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!