Spring-Boot-WebSocket
本文最后更新于:几秒前
问题
在 SpringBoot WebSocket 中, 我们使用常规注解, @ServerEndpoint
之后会出现无法注入的问题
解决方案
在上面写到我们需要补充 configuration 配置
1
2
3
4
5
6
7
8
9
10public class CdiAwareConfigurator extends ServerEndpointConfig.Configurator {
public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {
return CDI.current().select(endpointClass).get();
}
}
@ServerEndpoint(value = "/chat", configurator = CdiAwareConfigurator.class)
public class ChatEndpoint {
}Spring 提供的方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46@Bean
public class SpringWebSocketHandler extends WebSocketHandler {
final ConcurrentHashMap<String, WebSocketSession> hashMap = new ConcurrentHashMap<>();
@Override
public void afterConnectionEstablished(@NotNull WebSocketSession session) throws Exception {
hashMap.put(session.getId(), session);
}
@Override
public void handleMessage(@NotNull WebSocketSession session, @NotNull WebSocketMessage<?> message) throws Exception {
Object payload = message.getPayload();
session.sendMessage(new TextMessage("echo message" + LocalDateTime.now().toString()));
}
@Override
public void handleTransportError(@NotNull WebSocketSession session, @NotNull Throwable exception) throws Exception {
log.error("消息接受错误: {} , {}", session.getId(), exception.getMessage());
}
@Override
public void afterConnectionClosed(@NotNull WebSocketSession session, @NotNull CloseStatus closeStatus) throws Exception {
hashMap.remove(session.getId());
}
@Override
public boolean supportsPartialMessages() {
return false;
}
}
@ConditionalOnWebApplication
@Configuration
public class WebSocketConfigurator implements WebSocketConfigurer {
@Autowired
private SpringWebSocketHandler springWebSocketHandler;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(springWebSocketHandler, "/").setAllowedOrigins("*");
}
}
相关链接
Spring-Boot-WebSocket
https://zhengchalei.github.io/2023/01/02/Spring-Boot-WebSocket/