WebSocket 应用场景非常广泛,例如社交聊天、弹幕、多玩家游戏、协同编辑、股票基金实时报价、体育实况更新、视频会议/聊天、实时定位、在线教育、智能家居等,这些场景都与我们的生活息息相关。
ANY-IM 2.0 是基于 Spring Boot 2.X 框架开发的 WEB 在线即时通信应用,混合使用了 Spring MVC 及 Spring WebFLux,支持点对点通信、群通信、系统群发消息等多种方式。由于单体应用的局限性,又在单体应用的基础上设计了集群方案,解决资源合理利用的问题。
演示地址:https://www.ictgu.cn/
架构简单说明:
作为一名 Java 工程师,使用 Spring Boot 来构建单体应用无疑是最好的选择,简洁、高效、稳定!
1、工欲善其事必先利其器
2、创建 Spring Boot 应用
快速创建,参考官方文档 https://projects.spring.io/spring-boot/ ,为了加快开发速度,使用到 Lombok
、Jsoup
、Fastjson
等第三方依赖,开发时使用热部署,避免频繁地重启应用。
3、集成 WebSocket
org.springframework.boot
spring-boot-starter-websocket
前端需要使用 sockjs.js
、stomp.js
来连接 WebSocket, 推荐使用 Vue.js 来渲染前端页面。
入门 DEMO:https://spring.io/guides/gs/messaging-stomp-websocket/
STOMP协议详解:https://www.cnblogs.com/my_life/articles/7002138.html
4、集成 Spring Security 、Spring Session 及 MongoDB
需求 | 参考资料 | 官方文档 |
---|---|---|
Spring Security | Spring Security Demo | Spring Security |
Spring Session | Spring Session Data MongoDB | Spring Session |
MognoDB | Spring Boot 集成 MongoDB | docker 安装方式 |
MongoDB Web可视化工具:Mongo Express
首页 | Database 视图 | Collection 视图 | 编辑文档 |
---|---|---|---|
![]() |
![]() |
![]() |
![]() |
如图所示,小明和服务A建立了长连接,小红和服务B建立了长连接。此时,小明想给小红发消息,但是服务A和服务B之间互不关联,所以小明发给小红的消息会丢失。要想小明能联系到小红,就要实现服务A和服务B之间的通信。
跨服务间 WebSocket 通信实现
至此,小明就能到把消息发送给小红了。
WebSocket配置相关代码
/**
* WebSocket 配置
*/
@Configuration
@EnableScheduling
@EnableWebSocketMessageBroker
@Log4j2
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
private final WebSocketRepository webSocketRepository;
private final ServerConfiguration serverConfiguration;
public WebSocketConfig(WebSocketRepository webSocketRepository, ServerConfiguration serverConfiguration){
this.webSocketRepository = webSocketRepository;
this.serverConfiguration = serverConfiguration;
}
@Override
public void registerStompEndpoints(@Nullable StompEndpointRegistry registry) {
if (registry == null){
throw new RuntimeException("registry is null");
}
registry.addEndpoint("/any-socket").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry messageBrokerRegistry) {
messageBrokerRegistry.setApplicationDestinationPrefixes("/app");
messageBrokerRegistry.enableSimpleBroker("/topic", "/queue");
}
@Override
public void configureWebSocketTransport(final WebSocketTransportRegistration registration) {
registration.addDecoratorFactory(new WebSocketHandlerDecoratorFactory() {
@Override
public WebSocketHandler decorate(final WebSocketHandler handler) {
return new WebSocketHandlerDecorator(handler) {
/**
* 建立 WebSocket 连接之后
*/
@Override
public void afterConnectionEstablished(@Nullable final WebSocketSession session) throws Exception {
if (session == null){
throw new RuntimeException("session is null");
}
Principal principal = session.getPrincipal();
if (principal == null){
throw new RuntimeException("principal is null");
}
String username = principal.getName();
WebSocketSessionBean webSocketSessionBean = new WebSocketSessionBean(username, serverConfiguration.getServerId());
log.info("上线: " + username);
webSocketRepository.save(webSocketSessionBean);
super.afterConnectionEstablished(session);
}
/**
* 关闭 WebSocket 连接之后
*/
@Override
public void afterConnectionClosed(@Nullable WebSocketSession session, @Nullable CloseStatus closeStatus)
throws Exception {
if (session == null || closeStatus == null){
throw new RuntimeException("session isnull or closeStatus is null");
}
Principal principal = session.getPrincipal();
if (principal == null){
throw new RuntimeException("principal is null");
}
String username = principal.getName();
log.info("下线: " + username);
webSocketRepository.deleteByKeyAndValue(username, serverConfiguration.getServerId());
super.afterConnectionClosed(session, closeStatus);
}
};
}
});
super.configureWebSocketTransport(registration);
}
}
Docker Swarm 是 Docker 官网维护的集群管理工具,应用 Docker Swarm 可以很便捷地解决跨主机网络、动态扩容等问题。
入门文章可以参考:http://www.jianshu.com/p/096244610e15
如图所示,实现任意容器之间的网络互通,只需要两步即可。
1、在Docker Swarm 集群的 Manager 上创建网络
docker network create -d overlay --attachable [networkName]
2、启动容器时,带上网络参数
docker run --net [networkName] IMAGE
docker service create --network [networkName] IMAGE
动态扩容,也比较简单。
1、将 Spring Boot 应用构建成镜像
参考文章:http://www.jianshu.com/p/b06de710c109
2、在 Swarm 集群中启动
docker service create --name anyim --network [networkName] IMAGE
3、动态扩容
docker service scale anyim=[扩容数量]
Registrator:https://gliderlabs.com/registrator/latest/
Consul:https://www.consul.io/
1、启动服务注册中心 Consul
docker run -d --name=consul -p 8500:8500 --net [networkName] consul
启动完毕后,可以访问 http://localhost:8500/ 查看服务信息
2、启动 Registrator 监听 Docker 容器
docker run -d \
--name=registrator \
-v /var/run/docker.sock:/tmp/docker.sock \
--net [networkName] \
--link consul:consul \
registrator \
-cleanup=true \
-internal \
-resync=60 \
consul://consul:8500
3、使用 Consul Template 刷新 HAProxy 配置
此处,已封装好镜像,直接启动即可:
docker run -d \
--name consul-template-haproxy \
-p 8080:8080 \
--link consul:consul \
--net [networkName] \
registry.cn-hangzhou.aliyuncs.com/anoy/consul-template-haproxy
镜像地址:https://dev.aliyun.com/detail.html?spm=5176.1972343.2.2.jxJj3Q&repoId=87739
详见文章:http://www.jianshu.com/p/83036a320036
详见文章:http://www.jianshu.com/p/43d04d8baaf7
如有疑问,可以“评论”或者通过“简信”联系作者