如何使用Spring Boot WebSocket控制器每隔几秒钟安排一次“推送”指定数据?我目前有以下代码:
@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));
}
}
不幸的是,由于运行时引发了异常(java.lang.IllegalStateException: Encountered invalid @Scheduled method 'service': Only no-arg methods may be annotated with @Scheduled
),以上代码无法正常工作。
与@SubscribeMapping
批注不同,我无法从客户端传递目标变量(例如serviceId
),该客户端变量已订阅该方法以知道我必须订阅哪个“ service
” 。
按以下方式使用时,此方法效果很好:
@Scheduled(fixedDelay = 2000)
public void services() throws SQLException {
simpMessagingTemplate.convertAndSend("/topic/services", serviceService.getAllServices());
}
在后一种情况下,方法参数保持为空,并将所有服务的列表发送到客户端。
客户如何订阅特定的出版物(例如“ /topic/services/{serviceId}
”),然后定期接收相同的数据,直到客户最终取消订阅?