1.1引入netty依赖
io.netty netty-all 4.1.79.Final
2.netty实现websocket功能
public void start() {
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap serverBootstrap = new ServerBootstrap();
try {
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.localAddress(port)
.childHandler(new ChannelInitializer() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new ChunkedWriteHandler());
pipeline.addLast(new HttpObjectAggregator(64 * 1024));
// 核心的业务处理逻辑
pipeline.addLast(new TextWebSocketFrameHandler());
// 升级ws
// 注意该处理器与自定义业务处理器的顺序,如果需要获取http请求时的参数信息,该处理器应该位于http请求参数处理器之前
pipeline.addLast(new WebSocketServerProtocolHandler("/netty/toAll/websocket",true,10000L));
}
});
Channel channel = serverBootstrap.bind().syncUninterruptibly().channel();
channel.closeFuture().syncUninterruptibly();
} catch (Exception e) {
log.error("netty启动异常", e);
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.ImmediateEventExecutor;
import java.util.concurrent.ConcurrentHashMap;
public class ChannelPool {
public static final ChannelGroup CHANNEL_GROUP = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);
public static final ConcurrentHashMap USER_CHANNEL_MAP = new ConcurrentHashMap<>();
}
自定义业务处理器
import com.alibaba.fastjson.JSONObject; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; @Slf4j public class TextWebSocketFrameHandler extends SimpleChannelInboundHandlernetty服务手动注册到注册中心{ private String userId; @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ChannelPool.CHANNEL_GROUP.add(ctx.channel()); super.channelActive(ctx); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { ChannelPool.CHANNEL_GROUP.remove(ctx.channel()); if (userId != null) { ChannelPool.USER_CHANNEL_MAP.remove(userId); } super.channelInactive(ctx); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { FullHttpRequest request = (FullHttpRequest) msg; if (request.decoderResult().isSuccess() && Objects.equals("websocket", request.headers().get("Upgrade"))) { String uri = request.uri(); if (uri.contains("/toAll/websocket")) { String split = uri.split("\?")[0]; String[] split1 = split.split("/"); int length = split1.length; userId = split1[length - 1]; } } } super.channelRead(ctx,msg); } @Override protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame textWebSocketFrame) throws Exception { ChannelPool.CHANNEL_GROUP.writeAndFlush(new TextWebSocketFrame("连接netty----------->")); // TODO 发送消息业务逻辑 } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { log.error("netty连接异常", cause); ChannelPool.CHANNEL_GROUP.remove(ctx.channel()); ChannelPool.USER_CHANNEL_MAP.remove(userId); ctx.close(); } }
由于netty是集成到业务服务中的,且netty启动需要单独占用一个端口,无法与业务服务的端口公用,如需将netty实现的ws功能连接到网关,则需手动注册
public void init() throws UnknownHostException {
// nacos注册中心
NacosDiscoveryProperties nacosDiscoveryProperties = new NacosDiscoveryProperties();
// 服务名
nacosDiscoveryProperties.setService(serverName);
// 端口
nacosDiscoveryProperties.setPort(port);
// ip地址,容器化环境中获取ip地址可以使用spring-cloud-commons包中的inetUtils.findFirstNonLoopbackHostInfo().getIpAddress()
nacosDiscoveryProperties.setIp(InetAddress.getLocalHost().getHostAddress());
// 注册中心地址
nacosDiscoveryProperties.setServerAddr(serverAddress);
Registration registration = new NacosRegistration(null, nacosDiscoveryProperties, applicationContext);
nacosServiceRegistry.register(registration);
new Thread(this::start).start();
}
websocket连接网关
spring:
#配置网关
gateway:
discovery:
locator:
enabled: false
httpclient:
connect-timeout: 1000
response-timeout: 2s
#配置路由规则
routes:
- id: NACOS-NETTY
uri: lb:ws://netty-server
predicates:
- Path=/netty/toAll/**



