添加依赖
<repository>
<id>githubid>
<url>https://maven.pkg.github.comurl>
<snapshots>
<enabled>trueenabled>
snapshots>
repository>
<dependency>
<groupId>com.github.kuangcpgroupId>
<artifactId>netty-ws-spring-boot-starterartifactId>
<version>1.0.5-RELEASEversion>
dependency>
基础配置
netty-ws:
port: 5455
max-content-length: 4096
max-frame-size: 65536
reader-idle-sec: 60
reader-idle-threshold: 2
connect-auth: true
自定义连接处理类
@Component
@ChannelHandler.Sharable
public class DemoHandler extends AbstractBizHandler {
public DemoHandler(CacheDao cacheDao, UserDao userDao, WsServerConfig config) {
super(cacheDao, userDao, config);
this.schedulerPollQueueMsg(Executors.newScheduledThreadPool(1));
}
@Override
public void connectSuccess(Long userId) {
log.info("connected {}", userId);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
String id = WsSocketUtil.id(ctx);
Long userId = channelUserMap.get(id);
log.info("disconnect {}", userId);
super.channelInactive(ctx);
}
@Override
protected void handSharkHttpRequest(ChannelHandlerContext ctx, FullHttpRequest request) {
super.handSharkHttpRequest(ctx, request);
}
}
实现存储扩展 com.github.kuangcp.websocket.store.CacheDao
实现认证扩展 com.github.kuangcp.websocket.store.UserDao
ws://127.0.0.1:5455/ws?uid={uid}&token={token}
Netty作为通信基础,每个用户连接时通过前置的Nginx等SLB层负载均衡到WS集群。
注意:Redis可替换成任意中心存储, 已由 CacheDao 抽象,应用层自己实现。