当前位置: 首页 > 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));}}

相关文章:

  • NLP:BERT的介绍
  • Android Studio Dolphin 中Gradle下载慢的解决方法
  • Python中的机器学习:从入门到实战
  • 景联文科技精准数据标注:优化智能标注平台,打造智能未来
  • 神经网络(二):卷积神经网络
  • javaweb之会话管理
  • 睡眠:生命的隐形守护者
  • 【Linux】防火墙
  • 前段辅助工具分享(像素大厨)
  • 网络编程操作—函数
  • Comfyui 学习笔记2
  • react:React Hook函数
  • 【iOS】计算器的仿写
  • 秦巴山区SHP格式矢量范围
  • OpenCV视频I/O(4)视频采集类VideoCapture之获取异常处理模式函数getExceptionMode()的使用
  • ----------
  • 【面试系列】之二:关于js原型
  • 【跃迁之路】【444天】程序员高效学习方法论探索系列(实验阶段201-2018.04.25)...
  • 2018以太坊智能合约编程语言solidity的最佳IDEs
  • IDEA常用插件整理
  • JS正则表达式精简教程(JavaScript RegExp 对象)
  • php的插入排序,通过双层for循环
  • Vue组件定义
  • webpack入门学习手记(二)
  • 世界上最简单的无等待算法(getAndIncrement)
  • 我是如何设计 Upload 上传组件的
  • 责任链模式的两种实现
  • 带你开发类似Pokemon Go的AR游戏
  • ​ 无限可能性的探索:Amazon Lightsail轻量应用服务器引领数字化时代创新发展
  • # .NET Framework中使用命名管道进行进程间通信
  • # Kafka_深入探秘者(2):kafka 生产者
  • (2)从源码角度聊聊Jetpack Navigator的工作流程
  • (C语言)strcpy与strcpy详解,与模拟实现
  • (大众金融)SQL server面试题(1)-总销售量最少的3个型号的车及其总销售量
  • (附源码)apringboot计算机专业大学生就业指南 毕业设计061355
  • (免费领源码)python#django#mysql公交线路查询系统85021- 计算机毕业设计项目选题推荐
  • (三)centos7案例实战—vmware虚拟机硬盘挂载与卸载
  • (算法)区间调度问题
  • (一)ClickHouse 中的 `MaterializedMySQL` 数据库引擎的使用方法、设置、特性和限制。
  • (转载)OpenStack Hacker养成指南
  • ***通过什么方式***网吧
  • .NET MVC第三章、三种传值方式
  • .NET Reactor简单使用教程
  • .NET 实现 NTFS 文件系统的硬链接 mklink /J(Junction)
  • //TODO 注释的作用
  • @SpringBootApplication 包含的三个注解及其含义
  • [ 2222 ]http://e.eqxiu.com/s/wJMf15Ku
  • [ MSF使用实例 ] 利用永恒之蓝(MS17-010)漏洞导致windows靶机蓝屏并获取靶机权限
  • [20180224]expdp query 写法问题.txt
  • [ABP实战开源项目]---ABP实时服务-通知系统.发布模式
  • [Android] Binder 里的 Service 和 Interface 分别是什么
  • [bzoj1912]异象石(set)
  • [C#]猫叫人醒老鼠跑 C#的委托及事件
  • [CCF-CSP] 202303-4 星际网络II
  • [CLickhouse] 学习小计