gpt4 book ai didi

java - CopyOnWriteArrayList 为零而不是实际大小?

转载 作者:行者123 更新时间:2023-12-02 11:07:32 25 4
gpt4 key购买 nike

可能很简单,但我自己无法弄清楚。我有一些 Spring Boot WebSockets 实现示例,并且想要显示总 Activity session 。所以我创建了@Scheduled activeSessions任务,它应该显示实际计数,但它始终为 0。当 afterConnectionEstablished称为我得到预期的 session 大小。有什么问题吗?

@Configuration
public class Monitoring extends TextWebSocketHandler {

private List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message)
throws Exception {

String clientMessage = message.getPayload();
System.out.println(clientMessage);
sessions.forEach(s -> {
try {
s.sendMessage(new TextMessage("Hello! You session id is: " + s.getId()));
activeSessions();
} catch (IOException e) {
e.printStackTrace();
}
});
}

@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
//the messages will be broadcasted to all users.
System.out.println("Adding new session.");
sessions.add(session);
System.out.println("Current session count: " + sessions.size());
}

@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
sessions.remove(session);
}

@Scheduled(fixedRate = 2000)
public void activeSessions() {
System.out.println("Total sessions: " + sessions.size());
}
}

配置部分:

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(@NotNull WebSocketHandlerRegistry registry) {
registry.addHandler(new Monitoring(), "/socket");
}
}

到期conflict描述的自定义调度程序:

@Configuration
@EnableScheduling
public class SchedulingConfig {

// https://stackoverflow.com/questions/49343692/websocketconfigurer-and-scheduled-are-not-work-well-in-an-application

@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.setPoolSize(10);
taskScheduler.initialize();
return taskScheduler;
}
}

最佳答案

您当前有 Monitoring 类的 2 个独立实例。一个由您自己创建,执行请求处理(这不是 Spring 托管 bean!),另一个由 Spring 由于 @Configuration 检测到(这不应该是一个 @Component ?)。

删除 @Configuration 并将其替换为 @Bean 方法,这样您的 WebSocketConfig 如下所示

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

@Override
public void registerWebSocketHandlers(@NotNull WebSocketHandlerRegistry registry) {
registry.addHandler(monitoring(), "/socket");
}

@Bean
public Monitoring monitoring() {
return new Monitoring();
}
}

您现在拥有该 bean 的单个实例,由 Spring 管理。

关于java - CopyOnWriteArrayList 为零而不是实际大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50854630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com