Spring Boot快速整合Netty(一):配置启动

1、添加依赖

<!--netty-->
<dependency>
  <groupId>io.netty</groupId>
  <artifactId>netty-all</artifactId>
  <version>4.1.24.Final</version>
  <scope>compile</scope>
</dependency>

2、创建服务启动类


@Slf4j
@Component
public class TcpServer {

    private static class SingletonTcpServer {
        static final TcpServer instance = new TcpServer();
    }

    public static TcpServer getInstance() {
        return SingletonTcpServer.instance;
    }

    public void start(String ip, int port) {
        // master reactor
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        // sub reactor
        EventLoopGroup workGroup = new NioEventLoopGroup();

        ChannelFuture f;
        try {
            // start
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workGroup) // install NioEventLoopGroup
                    .channel(NioServerSocketChannel.class) // set channel type NIO
                    // set connect params
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    // set in/out event handler
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) {
                            // 添加分隔符解码器
                            ch.pipeline().addFirst(new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Unpooled.copiedBuffer("&&".getBytes())));
                            ch.pipeline().addLast(new TcpActiveHandler());
                            ch.pipeline().addLast(new TcpMsgInHandler());
                        }
                    });
            // bind port
            f = bootstrap.bind(ip, port).sync();
            if (f.isSuccess()) {
                log.info("start tcp server success: {}", port);
            } else {
                log.warn("start tcp server failed: {}", f.cause().getMessage());
            }
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("start tcp server error: {}", e.getMessage());
        } finally {
            workGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}

3、创建处理器

@Slf4j
@ChannelHandler.Sharable
public class TcpActiveHandler extends ChannelInboundHandlerAdapter {

    private final static AtomicLong activeCount = new AtomicLong(0);

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("active client count: {}", activeCount.addAndGet(1));
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        log.info("active client count: {}", activeCount.decrementAndGet());
    }

}
@Slf4j
public class TcpMsgInHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("client active: {}", ctx.channel().remoteAddress());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        log.info("client inactive: {}", ctx.channel().remoteAddress());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf byteBuf = (ByteBuf) msg;
        String readMsg = byteBuf.toString(CharsetUtil.UTF_8);

        // 业务代码
        ProduceMsg produceMsg = null;
        try {
            produceMsg = JSONObject.parseObject(readMsg, ProduceMsg.class);
        } catch (Exception e) {
            log.error("ProduceMsg 格式化消息失败!{}", e.getMessage());
            ctx.write(ERROR_FORMAT_MSG);
        }

        if (produceMsg != null) {
            log.info("Client Msg: {}", produceMsg);
            TestRecordTopVO testRecordTopVO;
            String msgType = produceMsg.getMsgType();
            String msgContent = produceMsg.getMsgContent();
            
        }

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("client {} exception: {}", ctx.channel().remoteAddress(), cause);
    }
}
@Data
public class ProduceMsg {

    /**
     * 消息类型
     */
    private String msgType;

    /**
     * 消息内容
     */
    private String msgContent;

}

4、创建Spring启动监听器

/**
 * ContextRefreshedEvent:
 * ApplicationContext被初始化或刷新时,该事件被发布。这也可以在ConfigurableApplicationContext接口中使用 refresh() 方法来发生。
 * 此处的初始化是指:所有的Bean被成功装载后处理Bean被检测并激活,所有Singleton Bean 被预实例化,ApplicationContext容器已就绪可用
 */
@Component
public class MainboardServerConfig implements ApplicationListener<ContextRefreshedEvent> {

    @Value("${netty.ip}")
    private String ip;

    @Value("${netty.port}")
    private int tcpPort;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ExecutorService service;
        service = Executors.newSingleThreadExecutor();
        service.submit(() -> TcpServer.getInstance().start(ip, tcpPort));
    }
}

最后运行SpringBoot项目即可!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Cloud可以很方便地与Netty框架进行整合,实现高并发、高性能的分布式系统。下面是一个简单的示例代码,演示了如何在Spring Cloud中使用Netty框架: 1. 首先,我们需要在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.65.Final</version> </dependency> ``` 2. 接下来,我们需要编写一个Netty服务器,用于接收来自客户端的请求。以下是一个简单的Netty服务器示例代码: ```java import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import org.springframework.stereotype.Component; @Component public class NettyServer { public void start(int port) throws Exception { // 创建两个EventLoopGroup,用于处理客户端和服务器端的I/O事件 EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { // 创建ServerBootstrap对象,用于启动服务器 ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new NettyServerHandler()); } }); // 绑定端口,启动服务器 ChannelFuture future = bootstrap.bind(port).sync(); // 等待服务器关闭 future.channel().closeFuture().sync(); } finally { // 关闭EventLoopGroup workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } } ``` 3. 接下来,我们需要编写一个Netty服务器处理程序,用于处理客户端发送的请求。以下是一个简单的处理程序示例代码: ```java import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; public class NettyServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf)msg; byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); String request = new String(bytes, "UTF-8"); System.out.println("Netty Server: " + request); String response = "Hello, Client!"; ctx.writeAndFlush(response); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } } ``` 4. 最后,我们需要在Spring Cloud应用程序中启动Netty服务器。以下是一个简单的Spring Boot应用程序示例代码: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringCloudNettyApplication implements CommandLineRunner { @Autowired private NettyServer nettyServer; public static void main(String[] args) { SpringApplication.run(SpringCloudNettyApplication.class, args); } @Override public void run(String... args) throws Exception { nettyServer.start(8888); } } ``` 这样,我们就可以在Spring Cloud应用程序中使用Netty框架。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值