[pravega-022] pravega源码分析--Controller子项目--关于netty[02]

2024-06-11 09:08

本文主要是介绍[pravega-022] pravega源码分析--Controller子项目--关于netty[02],希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.一个netty echo服务的例子。client向server发消息,server向client返回同样的消息。程序分两部分,server项目和client项目。这里包含了netty的核心要素。更多的细节请参考前文提到的参考资料即可。

2.server项目

2.1 目录结构

├── build.gradle
├── settings.gradle
└── src
    ├── main
        ├── java
           ├── EchoServerHandler.java
           └── Main.java
2.2 build.gradle文件内容

group 'com.brian.demo.netty'
version '1.0-SNAPSHOT'apply plugin: 'java'sourceCompatibility = 1.8repositories {mavenCentral()
}dependencies {compile group: 'io.netty', name: 'netty-all', version: '4.1.12.Final'testCompile group: 'junit', name: 'junit', version: '4.12'
}

2.3 Main.java文件内容

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
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 java.net.InetSocketAddress;//主要参考资料:
// 《netty in action》
// https://github.com/waylau/essential-netty-in-action
public class Main {private final int port;public Main(int port) {this.port = port;}public static void main(String args[]) throws Exception {new Main(8008).start();}public void start() throws Exception {//NioEventLoopGroup是一个线程池,一个线程可以处理多个channel,一个channel只对应一个线程EventLoopGroup group = new NioEventLoopGroup();//echo服务handlerfinal EchoServerHandler echoServerHandler = new EchoServerHandler();//创建 引导服务器ServerBootstrap sbs = new ServerBootstrap();try {//设置线程池sbs.group(group)//指定NIO传输的channel.channel(NioServerSocketChannel.class)//本地端口.localAddress(new InetSocketAddress(port))//配置handler pipeline。每个channel有一个pipline,// 包含多个handler,事件从pipline逐个经过handler进行处理。.childHandler(new ChannelInitializer<SocketChannel>() {@Overridepublic void initChannel(SocketChannel ch) throws Exception {ch.pipeline().addLast(echoServerHandler);}});//绑定服务器,然后同步等待服务器关闭。ChannelFuture future = sbs.bind().sync();System.out.println(Main.class.getName() +" started and listening for connections on " + future.channel().localAddress());//关闭channel,同步等待future.channel().closeFuture().sync();} finally {//释放线程池group.shutdownGracefully().sync();}}
}

2.4 EchoServerHandler.java文件内容

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;//Sharable注解,声明这个Handler的实例可以被多个channel共享使用
@ChannelHandler.Sharable
//ChannelInboundHandler接口,处理入站事件
public class EchoServerHandler extends ChannelInboundHandlerAdapter {//每个信息入站都会调用channelRead@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg){//收到的消息是Object msg,强转撑ByteBufByteBuf inBuf = (ByteBuf)msg;//在控制台输出接收到的消息System.out.println("Server received:" + inBuf.toString(CharsetUtil.UTF_8));//再把消息不做修改重新写给客户端。注意,此时数据还没有flush,仍然在服务端。ctx.write(inBuf);}//通知处理器,当下的channelread()读取消息是本批处理的最后一条消息的时候,调用本函数@Overridepublic void channelReadComplete(ChannelHandlerContext ctx) throws Exception {//把所有数据冲刷flush到客户端,关闭通道。至此操作完成。Listern以future方式通知操作完成。ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);}//读操作遇到异常@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {cause.printStackTrace();ctx.close();}
}

3. Client项目

3.1 文件目录结构

.
├── build.gradle
├── settings.gradle
└── src
    ├── main
        ├── java
            ├── EchoClientHandler.java
            └── Main.java
    
3.2 build.gradle文件内容

group 'com.brian.demo.netty'
version '1.0-SNAPSHOT'apply plugin: 'java'sourceCompatibility = 1.8repositories {mavenCentral()
}dependencies {compile group: 'io.netty', name: 'netty-all', version: '4.1.12.Final'testCompile group: 'junit', name: 'junit', version: '4.12'
}

3.3 Main.java文件内容

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;import java.net.InetSocketAddress;public class Main {private final String host;private final int port;public Main(){this.host="127.0.0.1";this.port=8008;}public void start() throws Exception{EventLoopGroup group = new NioEventLoopGroup();try {Bootstrap b = new Bootstrap();b.group(group).channel(NioSocketChannel.class).remoteAddress(new InetSocketAddress(host,port)).handler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ch.pipeline().addLast(new EchoClientHandler());}});ChannelFuture future = b.connect().sync();future.channel().closeFuture().sync();}finally {group.shutdownGracefully();}}public static void main(String args[])throws Exception{new Main().start();}
}

       

3.4 EchoClientHandler.java文件内容

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;@ChannelHandler.Sharable
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {System.out.println("client received:" + msg.toString(CharsetUtil.UTF_8));}@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {ctx.writeAndFlush(Unpooled.copiedBuffer("hello,world", CharsetUtil.UTF_8));}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {cause.printStackTrace();ctx.close();}
}

4. 如果遇到gradle不能导入nettty包的情况,关闭项目,删除~/.gradle目录所有文件,然后重新在idea做import项目即可。
   
   

这篇关于[pravega-022] pravega源码分析--Controller子项目--关于netty[02]的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1050735

相关文章

python panda库从基础到高级操作分析

《pythonpanda库从基础到高级操作分析》本文介绍了Pandas库的核心功能,包括处理结构化数据的Series和DataFrame数据结构,数据读取、清洗、分组聚合、合并、时间序列分析及大数据... 目录1. Pandas 概述2. 基本操作:数据读取与查看3. 索引操作:精准定位数据4. Group

MySQL中EXISTS与IN用法使用与对比分析

《MySQL中EXISTS与IN用法使用与对比分析》在MySQL中,EXISTS和IN都用于子查询中根据另一个查询的结果来过滤主查询的记录,本文将基于工作原理、效率和应用场景进行全面对比... 目录一、基本用法详解1. IN 运算符2. EXISTS 运算符二、EXISTS 与 IN 的选择策略三、性能对比

MySQL 内存使用率常用分析语句

《MySQL内存使用率常用分析语句》用户整理了MySQL内存占用过高的分析方法,涵盖操作系统层确认及数据库层bufferpool、内存模块差值、线程状态、performance_schema性能数据... 目录一、 OS层二、 DB层1. 全局情况2. 内存占js用详情最近连续遇到mysql内存占用过高导致

深度解析Nginx日志分析与499状态码问题解决

《深度解析Nginx日志分析与499状态码问题解决》在Web服务器运维和性能优化过程中,Nginx日志是排查问题的重要依据,本文将围绕Nginx日志分析、499状态码的成因、排查方法及解决方案展开讨论... 目录前言1. Nginx日志基础1.1 Nginx日志存放位置1.2 Nginx日志格式2. 499

Olingo分析和实践之EDM 辅助序列化器详解(最佳实践)

《Olingo分析和实践之EDM辅助序列化器详解(最佳实践)》EDM辅助序列化器是ApacheOlingoOData框架中无需完整EDM模型的智能序列化工具,通过运行时类型推断实现灵活数据转换,适用... 目录概念与定义什么是 EDM 辅助序列化器?核心概念设计目标核心特点1. EDM 信息可选2. 智能类

Olingo分析和实践之OData框架核心组件初始化(关键步骤)

《Olingo分析和实践之OData框架核心组件初始化(关键步骤)》ODataSpringBootService通过初始化OData实例和服务元数据,构建框架核心能力与数据模型结构,实现序列化、URI... 目录概述第一步:OData实例创建1.1 OData.newInstance() 详细分析1.1.1

Olingo分析和实践之ODataImpl详细分析(重要方法详解)

《Olingo分析和实践之ODataImpl详细分析(重要方法详解)》ODataImpl.java是ApacheOlingoOData框架的核心工厂类,负责创建序列化器、反序列化器和处理器等组件,... 目录概述主要职责类结构与继承关系核心功能分析1. 序列化器管理2. 反序列化器管理3. 处理器管理重要方

SpringBoot中六种批量更新Mysql的方式效率对比分析

《SpringBoot中六种批量更新Mysql的方式效率对比分析》文章比较了MySQL大数据量批量更新的多种方法,指出REPLACEINTO和ONDUPLICATEKEY效率最高但存在数据风险,MyB... 目录效率比较测试结构数据库初始化测试数据批量修改方案第一种 for第二种 case when第三种

解决1093 - You can‘t specify target table报错问题及原因分析

《解决1093-Youcan‘tspecifytargettable报错问题及原因分析》MySQL1093错误因UPDATE/DELETE语句的FROM子句直接引用目标表或嵌套子查询导致,... 目录报js错原因分析具体原因解决办法方法一:使用临时表方法二:使用JOIN方法三:使用EXISTS示例总结报错原

MySQL中的LENGTH()函数用法详解与实例分析

《MySQL中的LENGTH()函数用法详解与实例分析》MySQLLENGTH()函数用于计算字符串的字节长度,区别于CHAR_LENGTH()的字符长度,适用于多字节字符集(如UTF-8)的数据验证... 目录1. LENGTH()函数的基本语法2. LENGTH()函数的返回值2.1 示例1:计算字符串