大佬教程收集整理的这篇文章主要介绍了Spring Boot WebSocket:如何知道客户端何时取消订阅?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
您可以SessionUnsubscribeEvent
像这样收听事件:
@Controller
public class SessionUnsubscribeListener implements ApplicationListener<SessionUnsubscribeEvent> {
@OverrIDe
public voID onApplicationEvent(SessionUnsubscribeEvent event) {
Genericmessage message = (GenericmessagE) event.getmessage();
String simpDesTination = (String) message.getheaders().get("simpDesTination");
if ("/topic/service".equals(simpDesTination)) {
// do stuff
}
}
}
我目前有一个具有STOMP设置的简单WebSocket,其中客户端连接到主题(具有ID)。控制器立即响应要求的内容,并设置了一个变量来指示客户端已订阅的内容。@scheduled
现在,带有注释的方法每隔几秒钟就会向客户端发送一次请求。
在客户端第一次连接之前,计划的方法不会执行任何操作。但是,在第一次订阅后,无论是否订阅了客户端,它将继续发布。
@Controller
public class serviceWebSocketController {
@Autowired
private serviceservice serviceservice;
@Autowired
WebSocketSessionController webSocketSessionController;
@Autowired
private SimpmessagingTemplate simpmessagingTemplate;
private Set<Long> services = new HashSet<>();
@SubscribeMapping("/service/{servicEID}")
public serviceDTO subscribe(@DesTinationVariable("servicEID") final Long servicEID) throws SQLException {
System.out.println("Subscribed to service with ID: " + servicEID);
services.add(servicEID);
return serviceservice.getserviceWithProperties(servicEID).orElseThrow(() -> new resourceNotFoundException("service","id",servicEID));
}
@scheduled(fixedDelay = 2000)
public void service() throws SQLException {
services.removeIf(servicEID -> !webSocketSessionController.hasSubscriptionTo("/topic/service/" + servicEID));
// Publish specified service data to each anonymously subscribed client.
services.forEach(servicEID -> {
try {
System.out.println("Publishing service with ID: " + servicEID);
// We don't use .convertAndSendToUser here,because all our clients are anonymous.
simpmessagingTemplate.convertAndSend("/topic/service/" + servicEID,serviceservice.getserviceWithProperties(servicEID));
} catch (SQLException E) {
e.printStackTrace();
}
});
}
}
如何判断客户是否已取消订阅?
如果@UnsubscribeMapping
存在类似的东西,我可以简单地将currentSubscriptionservicEID
变量null
再次设置为,以防止调度的方法连续发布数据。
以上是大佬教程为你收集整理的Spring Boot WebSocket:如何知道客户端何时取消订阅?全部内容,希望文章能够帮你解决Spring Boot WebSocket:如何知道客户端何时取消订阅?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。