Bootstrap

java websocket 微服务_微服务-springboot+websocket在线聊天室

一.引入依赖

org.springframework.boot

spring-boot-starter-websocket

二.注入ServerEndpointExporter

编写一个WebSocketConfig配置类,注入对象ServerEndpointExporter,

这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint

importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.web.socket.server.standard.ServerEndpointExporter;/*** @Description: 编写一个WebSocketConfig配置类,注入对象ServerEndpointExporter,

* 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint*/@Configurationpublic classWebSocketConfig {

@BeanpublicServerEndpointExporter serverEndpointExporter() {return newServerEndpointExporter();

}

}

三.websocket的具体实现类

使用springboot的唯一区别是要@Component声明下,而使用独立容器是由容器自己管理websocket的,

但在springboot中连容器都是spring管理的。

虽然@Component默认是单例模式的,但springboot还是会为每个websocket连接初始化一个bean,

所以可以用一个静态set保存起来。

importorg.springframework.stereotype.Component;import javax.websocket.*;importjavax.websocket.server.ServerEndpoint;importjava.util.concurrent.CopyOnWriteArraySet;/*** * @Description: websocket的具体实现类

* * 使用springboot的唯一区别是要@Component声明下,而使用独立容器是由容器自己管理websocket的,

* * 但在springboot中连容器都是spring管理的。

* 虽然@Component默认是单例模式的,但springboot还是会为每个websocket连接初始化一个bean,

* 所以可以用一个静态set保存起来。*/@ServerEndpoint(value= "/websocket")

@Componentpublic classMyWebSocket {//用来存放每个客户端对应的MyWebSocket对象。

private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet();//与某个客户端的连接会话,需要通过它来给客户端发送数据

privateSession session;/*** 连接建立成功调用的方法*/@OnOpenpublic voidonOpen(Session session) {this.session =

;