is not a @Sharable handler解决方法

本文记录了一次在使用Netty框架时遇到的关于编码器和解码器的问题,特别是在与Spring框架整合时,不当使用@Autowired注解注入单例导致的错误及解决方法。介绍了如何正确地为每个连接创建新的实例来避免此类问题。
Seed-Coder-8B-Base

Seed-Coder-8B-Base

文本生成
Seed-Coder

Seed-Coder是一个功能强大、透明、参数高效的 8B 级开源代码模型系列,包括基础变体、指导变体和推理变体,由字节团队开源

昨天在写编码器的时候,因为是和spring整合,因此在使用编码的时候用Autowired自动注入

@Autowired
private ProtocolDecoder protocolDecoder ;

@Autowired
private ProtocolEncoder protocolEncoder;

结果在多个客户端连接(其实不是多客户端的问题)的时候导致一直在报错,如下

io.netty.channel.ChannelPipelineException: com.sim.server.game.net.coder.decoder.ProtocolDecoder is not a @Sharable handler, so can't be added or removed multiple times.

于是我就自作聪明的将ProtocolDecoder上加了个@Sharable注解,结果在启动的时候就报错了。

Caused by: java.lang.IllegalStateException: ChannelHandler com.sim.server.game.net.coder.decoder.ProtocolDecoder is not allowed to be shared

最后的解决方法是,不要使用单例了,每次添加handler的时候直接new

        pipeline.addLast("decoder",new ProtocolDecoder() );
        pipeline.addLast("encoder",new ProtocolEncoder()) ;

当然如果是在ChannelInitializer的子类报错说is not a @Sharable handler,一般情况加上@Sharable注解即可。

您可能感兴趣的与本文相关的镜像

Seed-Coder-8B-Base

Seed-Coder-8B-Base

文本生成
Seed-Coder

Seed-Coder是一个功能强大、透明、参数高效的 8B 级开源代码模型系列,包括基础变体、指导变体和推理变体,由字节团队开源

package com.hlyt.hp.handler; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.hlyt.hp.domain.Sensor; import com.hlyt.hp.domain.dto.SensorActualValueLogDTO; import com.hlyt.hp.mapper.SensorMapper; import com.hlyt.hp.service.ISensorActualValueLogService; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.math.BigDecimal; import java.util.concurrent.CompletableFuture; /** * Netty 服务端处理器 * @Author: liuze * @Date: 2025/7/28 */ @Component @ChannelHandler.Sharable public class NettyServerHandler extends ChannelInboundHandlerAdapter { @Autowired private ISensorActualValueLogService sensorActualValueLogService; @Autowired private SensorMapper sensorMapper; @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("--------------------------aaaa--------------------------"); // 异步处理设备发送的数据 CompletableFuture.runAsync(() -> { try { System.out.println("收到客户端消息:" + msg); ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(String.valueOf(msg)); // 获取各个字段的值 String sensorCode = jsonNode.get("sensor_code").asText(); String sensorValue = jsonNode.get("sensor_value").asText(); Sensor sensor = sensorMapper.selectSensorByCode(sensorCode); if(sensor == null){ throw new RuntimeException("未查询到传感器编码对应的传感器"); } Long id = sensor.getId(); SensorActualValueLogDTO sensorActualValueLogDTO = new SensorActualValueLogDTO(); sensorActualValueLogDTO.setSensorId(id); BigDecimal bigDecimalValue = new BigDecimal(sensorValue); sensorActualValueLogDTO.setSensorValue(bigDecimalValue); // 记录传感器实际值 sensorActualValueLogService.insertSensorActualValueLog(sensorActualValueLogDTO); } catch (Exception e) { e.printStackTrace(); } }); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } } 加入websocket发送给前端
最新发布
08-12
为了在 `NettyServerHandler` 中集成 WebSocket 服务器功能,以便向前端发送消息,可以按照以下步骤进行实现。这些步骤基于 Netty 的 WebSocket 协议支持,并结合现有的 `NettyServerHandler` 结构进行扩展。 ### 1. 引入必要的依赖 确保项目中已经引入了 Netty 的 WebSocket 协议支持模块。如果使用 Maven,需要在 `pom.xml` 中添加以下依赖: ```xml <dependency> <groupId>io.netty</groupId> <artifactId>netty-codec-http</artifactId> <version>4.1.89.Final</version> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-codec-http-websocketx</artifactId> <version>4.1.89.Final</version> </dependency> ``` ### 2. 修改 `NettyServerHandler` 以支持 WebSocket 握手 `NettyServerHandler` 需要处理 HTTP 升级请求,以完成 WebSocket 握手过程。可以在 `channelRead0` 方法中判断请求是否为 WebSocket 请求,并执行相应的握手逻辑。 ```java public class NettyServerHandler extends SimpleChannelInboundHandler<Object> { private WebSocketServerHandshaker handshaker; @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { handleHttpRequest(ctx, (FullHttpRequest) msg); } else if (msg instanceof WebSocketFrame) { handleWebSocketFrame(ctx, (WebSocketFrame) msg); } } private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { if (!req.decoderResult().isSuccess() || !"websocket".equals(req.headers().get("Upgrade"))) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST)); return; } WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( getWebSocketLocation(req), null, true); handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), req); } } private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { if (res.status().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf); buf.release(); } ChannelFuture f = ctx.channel().writeAndFlush(res); if (!isKeepAlive(req) || res.status().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } } private static boolean isKeepAlive(FullHttpRequest req) { return HttpUtil.isKeepAlive(req); } private static String getWebSocketLocation(FullHttpRequest req) { String location = req.headers().get(HttpHeaderNames.HOST) + req.uri(); return "ws://" + location; } } ``` ### 3. 处理 WebSocket 消息帧 在握手完成后,所有后续的消息将以 `WebSocketFrame` 的形式传递。可以通过重写 `handleWebSocketFrame` 方法来处理不同类型的消息帧,例如文本帧、二进制帧等。 ```java private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (!(frame instanceof TextWebSocketFrame)) { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName())); } String request = ((TextWebSocketFrame) frame).text(); System.out.println("收到客户端消息: " + request); // 向客户端发送响应 ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器收到: " + request)); } ``` ### 4. 维护连接状态并发送消息 为了能够向前端发送消息,可以维护一个 `Channel` 的集合,记录所有连接的客户端。可以参考引用中的思路,使用一个 `Map` 来保存连接的客户端通道,并在需要时通过 `Channel` 发送消息 [^3]。 ```java public class NettyServerHandler extends SimpleChannelInboundHandler<Object> { private static final Map<String, Channel> clients = new ConcurrentHashMap<>(); private WebSocketServerHandshaker handshaker; @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { // 当客户端连接时,可以生成唯一标识符并存储 String clientId = UUID.randomUUID().toString(); clients.put(clientId, ctx.channel()); System.out.println("客户端连接,ID: " + clientId); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { // 当客户端断开连接时,从Map中移除 clients.forEach((key, value) -> { if (value.equals(ctx.channel())) { clients.remove(key); System.out.println("客户端断开连接,ID: " + key); } }); } // 其他方法保持不变 } ``` ### 5. 发送消息给前端 在需要向前端发送消息时,可以直接从 `clients` 中获取 `Channel` 并调用 `writeAndFlush` 方法发送 `TextWebSocketFrame`。 ```java public static void sendMessageToClient(String clientId, String message) { Channel channel = clients.get(clientId); if (channel != null && channel.isActive()) { channel.writeAndFlush(new TextWebSocketFrame(message)); } } ``` ### 6. 心跳检测与连接管理 为了确保连接的稳定性,可以引入心跳检测机制。Netty 提供了 `IdleStateHandler`,可以用于检测读写空闲状态,并在超时后触发事件 [^4]。 ```java public class HeartbeatNettyHandler extends ChannelInboundHandlerAdapter { @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { IdleStateEvent event = (IdleStateEvent) evt; switch (event.state()) { case READER_IDLE: System.out.println("读空闲,关闭连接"); ctx.channel().close(); break; case WRITER_IDLE: System.out.println("写空闲,发送心跳"); ctx.channel().writeAndFlush(new PingWebSocketFrame(Unpooled.EMPTY_BUFFER)); break; case ALL_IDLE: System.out.println("读写空闲"); break; } } } } ``` 在 `NettyServerInitializer` 中添加 `IdleStateHandler`,并注册 `HeartbeatNettyHandler`: ```java public class NettyServerInitializer extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new HttpObjectAggregator(65536)); pipeline.addLast(new WebSocketServerProtocolHandler("/websocket")); pipeline.addLast(new IdleStateHandler(0, 5, 0, TimeUnit.SECONDS)); // 5秒写空闲 pipeline.addLast(new HeartbeatNettyHandler()); pipeline.addLast(new NettyServerHandler()); } } ``` ### 总结 通过上述步骤,可以在 `NettyServerHandler` 中集成 WebSocket 服务器功能,并实现向前端发送消息的能力。主要涉及以下几个方面: - WebSocket 握手处理 [^4] - WebSocket 消息帧的解析与响应 - 客户端连接状态管理 - 心跳检测与连接维护 [^3]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值