当前位置: 首页 > news >正文

springboot引入netty

配置类

import cn.hutool.core.thread.ThreadUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;import javax.annotation.PostConstruct;
import javax.annotation.Resource;@Component
@Slf4j
public class NettyServerConfig {@Resourceprivate BizHandler bizHandler;@Value("${netty.port}")private int port;@PostConstructpublic void start(){ThreadUtil.newSingleExecutor().execute(this::doStart);}public void doStart(){ServerBootstrap serverBootstrap = new ServerBootstrap();EventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workGroup = new NioEventLoopGroup();serverBootstrap.group(bossGroup,workGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024).childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).childHandler(new ChannelInitializer<SocketChannel>(){@Overrideprotected void initChannel(SocketChannel socketChannel) {ChannelPipeline pipeline = socketChannel.pipeline();pipeline.addFirst(bizHandler);}});ChannelFuture channelFuture;try {channelFuture = serverBootstrap.bind(port).sync();} catch (InterruptedException e) {throw new RuntimeException(e);}channelFuture.addListener(future -> {if(future.isSuccess()){log.info("netty服务 启动成功");}});ChannelFuture closeFuture = channelFuture.channel().closeFuture();try {closeFuture.sync();} catch (InterruptedException e) {e.printStackTrace();}finally {bossGroup.shutdownGracefully();workGroup.shutdownGracefully();}}
}

处理器

import com.google.common.collect.Lists;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;@Slf4j
@Service
@ChannelHandler.Sharable
public class BizHandler extends ChannelInboundHandlerAdapter {private static final String SPACE = " ";private static final ConcurrentHashMap<ChannelHandlerContext, String> channelContextMap = new ConcurrentHashMap<>();public void send(){channelContextMap.entrySet().forEach(e -> {ChannelHandlerContext context = e.getKey();ByteBuf buf = context.alloc().buffer();byte[] dataFrame = generateDataFrame();buf.writeBytes(dataFrame);context.channel().writeAndFlush(buf);});}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) {ByteBuf buffer = (ByteBuf) msg;byte[] bytes = new byte[buffer.readableBytes()];buffer.readBytes(bytes);String msgHexStr = this.byteArrayToHexString(bytes);//如果不是预期的连接发过来消息 主动断开连接//ctx.channel().close();ctx.fireChannelRead(msg);}@Overridepublic void channelInactive(ChannelHandlerContext ctx) {channelContextMap.remove(ctx);}private String byteArrayToHexString(byte[] bytes) {List<String> dataFrame = Lists.newArrayList();for (byte b : bytes) {String hex = Integer.toHexString(0xFF & b);if (hex.length() == 1) {// 如果是一位的话,要补0hex = "0" + hex;}dataFrame.add(hex.toUpperCase());}return dataFrame.stream().collect(Collectors.joining(SPACE));}}

http://www.mrgr.cn/news/37515.html

相关文章:

  • CentOS Linux教程(8)--使用tar压缩解压文件
  • 论文解析_客户分组对商业银行个人信用评分模型的提升作用研究,作者张亚京-中国人民银行征信中心博士后工作站
  • StopWath,apache commons lang3 包下的一个任务执行时间监视器的使用
  • 照片压缩方法分享,掌握这些小技巧轻松压缩
  • 浙大数据结构:06-图3 六度空间
  • 技术疑问:为什么在现在的spring代码当中几乎没有看到Applicationcontext了
  • 极狐GitLab 17.4 重点功能解读【九】
  • 【新进展】护理临床智能决策系统:大语言模型与本地知识库的融合与应用
  • 【AI战略思考5】工欲善其事,必先利其器。我的利器是什么?
  • 华为 HCIP-Datacom H12-821 题库 (28)
  • spring第一个入门框架
  • 新一代的程序员如何培养自己的核心竞争力?(一)
  • 2024年11月30日,PMI(PMP项目管理国际认证)考试报名攻略!
  • 从GPS接收机灵敏度出发--理论计算GPS最低的跟踪灵敏度
  • Uptime Kuma运维监控服务本地部署结合内网穿透实现远程在线监控
  • 部标主动安全(ADAS+DMS)对接说明
  • ​​合​​合​​信​息​​​龙​​湖​​数​​科​​一​​面​​​
  • 【1分钟学会】实用的Git工作流程
  • 本地生活服务项目揭秘!谁搭建的本地生活服务商作业系统收益效果好?
  • windows 在哪里改MongoDB 配置文件?