当前位置: 首页 > 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.lryc.cn/news/447621.html

相关文章:

  • PWM基础与信号控制
  • nvm,一款nodejs版本管理工具
  • 数据处理与统计分析篇-day11-RFM模型案例
  • 【PostgreSQL】PostgreSQL数据库允许其他IP连接到数据库(Windows Linux)
  • 通义千问:让我的编程工作效率翻倍的秘密武器
  • 2.Seata 1.5.2 集成Springcloud-alibaba
  • python 图像绘制问题: 使用turtle库绘制蟒蛇
  • 大模型分布式训练并行技术(七)-自动并行
  • 网络安全等级保护 | 规范企业网络系统安全使用 | 天锐股份助力等保制度落地
  • Springboot使用redis,以及解决redis缓存穿透,击穿,雪崩等问题
  • pve 命令开启关闭虚拟机
  • 【达梦数据库】临时表的使用测试
  • 【GUI设计】基于Matlab的图像去噪GUI系统(8),matlab实现
  • 【计算机科学导论】
  • 【C++】I/O流的使用介绍
  • 深度学习:(八)深层神经网络参数与流程
  • `pattern = r“(\d+)(CNY|JPY|HKD|EUR|GBP|fen|cents|sen|eurocents|pence)“
  • 宝塔面板部署雷池社区版教程
  • 【击败100%】258. 各位相加
  • 【alist】宝塔面板docker里的alist默认admin无法登录
  • 【击败100%】1281. 整数的各位积和之差
  • Flink基本概念和算子使用
  • Kafka 3.0.0集群部署教程
  • 昇思MindSpore进阶教程-格式转换
  • 搜索软件 Everything 的安装与使用教程
  • oracle 如何判断当前时间在27号到当月月底
  • Django 配置邮箱服务,实现发送信息到指定邮箱
  • Git使用手册
  • sql-labs靶场
  • 【Redis入门到精通二】Redis核心数据类型(String,Hash)详解