Rpc原理详解

博客上已经有人解释的很详细了,我就不在解释了。传送门

项目简介

项目是依赖于.net core2.0版本,内部都是依靠IOC来实现的,方便做自定义扩展。底层的通信是采用socket,sokcet的代码参考Enode的socket代码。类的序列化目前只支持自带的BinarySerializer和Json.net,也可以自定义,扩展也很方便。也支持zookeeper的服务协调。

框架传输及序列化逻辑

当客户端发起请求时,根据建立的客户端代理,获取当前的请求方法信息(名字、所属类型、参数值),通过自带的BinarySerializer将其序列化,所以在传输的方法中的自定义的类就必须加上【Serializable】可序列化标记,不然会报错。客户端将请求的方法信息序列化成字节数组之后传输到服务端,服务端获取到信息后根据方法信息获取到要执行的方法,然后执行该方法,并将结果返回给客户端。返回结果的序列化可以采用自定义的标记来进行,比如在方法或者类上面打上【BinarySerializer】标记,则采用BinarySerializer序列化,打上【JsonSerializer】标记则采用json.net来序列化话,后期可以支持protobuf来序列化。

服务端代码

首先定义一个接口和一个实现类

namespace NetCoreRpc.Application
{
public interface IStudentApplication
{
int Age(); bool IsYongPeople(int age); void Say(string msg); Task Sleep(); Task<int> RunAsync(int sleepTime); void Say(byte[] msg); byte[] Say(); [BinarySerializer]
TestModel Test();
} public class StudentApplication : IStudentApplication
{
public int Age()
{
return ;
} public bool IsYongPeople(int age)
{
return age < ;
} public async Task<int> RunAsync(int sleepTime)
{
await Task.Delay(sleepTime);
return sleepTime;
} public void Say(string msg)
{
Console.WriteLine($"Say:{msg}");
} public Task Sleep()
{
return Task.Delay();
} public void Say(byte[] msg)
{
Console.WriteLine(Encoding.UTF8.GetString(msg));
} public byte[] Say()
{
return Encoding.UTF8.GetBytes("Good Job!");
} public TestModel Test()
{
return new TestModel
{
Age = ,
Msg = Encoding.UTF8.GetBytes("Hello")
};
}
} [Serializable]
public class TestModel
{
public int Age { get; set; } public byte[] Msg { get; set; } public override string ToString()
{
return $"{Age}|{Encoding.UTF8.GetString(Msg)}";
}
}
}

IStudentApplication

不基于zookeeper的服务端版本

    internal class Program
{
public static IConfigurationRoot Configuration; private static void Main(string[] args)
{
Console.WriteLine("请输入监听端口:");
var strPort = Console.ReadLine();
var builder = new ConfigurationBuilder();
//.SetBasePath(Path.Combine(AppContext.BaseDirectory)).AddJsonFile("NetCoreRpc.json", optional: true);
Configuration = builder.Build();
var servicesProvider = BuildDi();
DependencyManage.SetServiceProvider(servicesProvider, Configuration);
NRpcServer nrpcServer = new NRpcServer(int.Parse(strPort));
nrpcServer.Start("NetCoreRpc.Application");
Console.WriteLine("Welcome to use NetCoreRpc!");
Console.WriteLine("Input exit to exit");
var str = Console.ReadLine();
while (!string.Equals(str, "exit", StringComparison.OrdinalIgnoreCase))
{
str = Console.ReadLine();
}
nrpcServer.ShutDown();
} private static IServiceProvider BuildDi()
{
IServiceCollection services = new ServiceCollection(); services.AddSingleton<ILoggerFactory, LoggerFactory>();
services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
services.AddSingleton<IStudentApplication, StudentApplication>();
services.UseRpc();
//.UseZK();
var serviceProvider = services.BuildServiceProvider(); var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>(); loggerFactory.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true });
loggerFactory.ConfigureNLog("NLog.config"); return serviceProvider;
}
}

Server

基于zookeeper的服务端版本

    internal class Program
{
public static IConfigurationRoot Configuration; private static void Main(string[] args)
{
Console.WriteLine("请输入监听端口:");
var strPort = Console.ReadLine();
var builder = new ConfigurationBuilder()
.SetBasePath(Path.Combine(AppContext.BaseDirectory)).AddJsonFile("NetCoreRpc.json", optional: true);
Configuration = builder.Build();
var servicesProvider = BuildDi();
DependencyManage.SetServiceProvider(servicesProvider, Configuration);
NRpcServer nrpcServer = new NRpcServer(int.Parse(strPort));
nrpcServer.Start("NetCoreRpc.Application");
Console.WriteLine("Welcome to use NetCoreRpc!");
Console.WriteLine("Input exit to exit");
var str = Console.ReadLine();
while (!string.Equals(str, "exit", StringComparison.OrdinalIgnoreCase))
{
str = Console.ReadLine();
}
nrpcServer.ShutDown();
} private static IServiceProvider BuildDi()
{
IServiceCollection services = new ServiceCollection(); services.AddSingleton<ILoggerFactory, LoggerFactory>();
services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
services.AddSingleton<IStudentApplication, StudentApplication>();
services.UseRpc()
.UseZK();
var serviceProvider = services.BuildServiceProvider(); var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>(); loggerFactory.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true });
loggerFactory.ConfigureNLog("NLog.config"); return serviceProvider;
}
}

基于zookeeper的版本

客户端代码

首先要引用刚刚定义的接口和Model

    internal class Program
{
public static IConfigurationRoot Configuration; private static void Main(string[] args)
{
var builder = new ConfigurationBuilder().SetBasePath(Path.Combine(AppContext.BaseDirectory)).AddJsonFile("NetCoreRpc.json", optional: true);
Configuration = builder.Build(); var servicesProvider = BuildDi();
DependencyManage.SetServiceProvider(servicesProvider, Configuration); Console.WriteLine("Welcome to use NetCoreRpc!");
var studentApplication = ProxyFactory.Create<IStudentApplication>();
Console.WriteLine(studentApplication.Age());
Console.WriteLine(studentApplication.IsYongPeople());
var runTask = studentApplication.RunAsync();
studentApplication.Say("Hello world");
studentApplication.Say(Encoding.UTF8.GetBytes("Hi!"));
Console.WriteLine(Encoding.UTF8.GetString(studentApplication.Say()));
var test = studentApplication.Test();
Console.WriteLine(test.ToString());
studentApplication.Sleep();
Console.WriteLine(runTask.Result); Console.WriteLine("Input exit to exit");
var str = Console.ReadLine();
while (!string.Equals(str, "exit", StringComparison.OrdinalIgnoreCase))
{
str = Console.ReadLine();
}
} private static IServiceProvider BuildDi()
{
IServiceCollection services = new ServiceCollection();
services.AddOptions();
services.Configure<RemoteEndPointConfig>(Configuration.GetSection("NetCoreRpc"));
services.AddSingleton<ILoggerFactory, LoggerFactory>();
services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
services.UseRpc().UseZK();
var serviceProvider = services.BuildServiceProvider(); var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>(); //configure NLog
loggerFactory.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true });
loggerFactory.ConfigureNLog("NLog.config"); return serviceProvider;
}
}

客户端基于zookeeper

{
"NetCoreRpc": {
"Default": "192.168.129.194:12346,192.168.129.194:12347,192.168.129.194:12348",
"Group": [
{
"NameSpace": "",
"Address": "127.0.0.1:12345"
}
],
"Zookeeper": {
"Connection": "192.168.100.34:2181",
"ParentName": "/NetCoreRpc/ClientTest"
}
}
}

NetCoreRpc.json

    internal class Program
{
public static IConfigurationRoot Configuration; private static void Main(string[] args)
{
var builder = new ConfigurationBuilder().SetBasePath(Path.Combine(AppContext.BaseDirectory)).AddJsonFile("NetCoreRpc.json", optional: true);
Configuration = builder.Build(); var servicesProvider = BuildDi();
DependencyManage.SetServiceProvider(servicesProvider, Configuration); Console.WriteLine("Welcome to use NetCoreRpc!");
var studentApplication = ProxyFactory.Create<IStudentApplication>();
Console.WriteLine(studentApplication.Age());
Console.WriteLine(studentApplication.IsYongPeople());
var runTask = studentApplication.RunAsync();
studentApplication.Say("Hello world");
studentApplication.Say(Encoding.UTF8.GetBytes("Hi!"));
Console.WriteLine(Encoding.UTF8.GetString(studentApplication.Say()));
var test = studentApplication.Test();
Console.WriteLine(test.ToString());
studentApplication.Sleep();
Console.WriteLine(runTask.Result); Console.WriteLine("Input exit to exit");
var str = Console.ReadLine();
while (!string.Equals(str, "exit", StringComparison.OrdinalIgnoreCase))
{
str = Console.ReadLine();
}
} private static IServiceProvider BuildDi()
{
IServiceCollection services = new ServiceCollection();
services.AddOptions();
services.Configure<RemoteEndPointConfig>(Configuration.GetSection("NetCoreRpc"));
services.AddSingleton<ILoggerFactory, LoggerFactory>();
services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
services.UseRpc();//.UseZK();
var serviceProvider = services.BuildServiceProvider(); var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>(); //configure NLog
loggerFactory.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true });
loggerFactory.ConfigureNLog("NLog.config"); return serviceProvider;
}
}

不基于zookeeper的代码

NetCoreRpc.json中的Zookeeper节点可以不用配置

调用测试结果

服务端输出如下:

客户端输出如下:

项目中感觉不足之处

1、传输时采用的序列化采用的是自带的BinarySerializer,需要在每个Model打上可序列化标记,后期希望改成不需要打标记就可以序列化的

2、采用zookeeper时,获取可用IP是获取当前第一个可用的IP,没有有任何的算法

3、其它目前还没有想到,如果各位博友有什么建议可以提一下,帮助我一下,谢谢

项目源码地址

GitHub

今天晚上在写这篇随笔的时候发现自己无从下手,博友有没有支招的啊,非常感谢。

基于.netcore 开发的轻量Rpc框架的更多相关文章

  1. Cardinal:一个用于移动项目开发的轻量 CSS 框架

    Cardinal 是一个适用于移动项目的 CSS 框架,包含很多有用的默认样式.矢量字体.可重用的模块以及一个简单的响应式模块系统.Cardinal 提供了一种在多种移动设备上实现可伸缩的字体和布局的 ...

  2. 基于Node和Electron开发了轻量版API接口请求调试工具——Post-Tool

    Electron 是一个使用 JavaScript.HTML 和 CSS 构建桌面应用程序的框架. 嵌入 Chromium 和 Node.js 到 二进制的 Electron 允许您保持一个 Java ...

  3. vue-calendar 基于 vue 2.0 开发的轻量,高性能日历组件

    vue-calendar-component 基于 vue 2.0 开发的轻量,高性能日历组件 占用内存小,性能好,样式好看,可扩展性强 原生 js 开发,没引入第三方库 Why Github 上很多 ...

  4. 基于HTTP/2和protobuf的RPC框架:GRPC

    谷歌发布的首款基于HTTP/2和protobuf的RPC框架:GRPC Google 刚刚开源了grpc,  一个基于HTTP2 和 Protobuf 的高性能.开源.通用的RPC框架.Protobu ...

  5. 基于.NetCore开发博客项目 StarBlog - (2) 环境准备和创建项目

    系列文章 基于.NetCore开发博客项目 StarBlog - (1) 为什么需要自己写一个博客? 基于.NetCore开发博客项目 StarBlog - (2) 环境准备和创建项目 ... 基于. ...

  6. 基于.NetCore开发博客项目 StarBlog - (3) 模型设计

    系列文章 基于.NetCore开发博客项目 StarBlog - (1) 为什么需要自己写一个博客? 基于.NetCore开发博客项目 StarBlog - (2) 环境准备和创建项目 基于.NetC ...

  7. 基于.NetCore开发博客项目 StarBlog - (6) 页面开发之博客文章列表

    系列文章 基于.NetCore开发博客项目 StarBlog - (1) 为什么需要自己写一个博客? 基于.NetCore开发博客项目 StarBlog - (2) 环境准备和创建项目 基于.NetC ...

  8. 基于.NetCore开发博客项目 StarBlog - (9) 图片批量导入

    系列文章 基于.NetCore开发博客项目 StarBlog - (1) 为什么需要自己写一个博客? 基于.NetCore开发博客项目 StarBlog - (2) 环境准备和创建项目 基于.NetC ...

  9. 基于.NetCore开发博客项目 StarBlog - (11) 实现访问统计

    系列文章 基于.NetCore开发博客项目 StarBlog - (1) 为什么需要自己写一个博客? 基于.NetCore开发博客项目 StarBlog - (2) 环境准备和创建项目 基于.NetC ...

随机推荐

  1. 使用VSCode创建Asp.Net Core

    前言 .Net Core 2.0已经发布几个月了,惭愧!身为一个开发人员现在才开始接触,有人说有VS这一宇宙第一IDE在,为啥还要用VSCode,为啥?因为我们是程序猿啊!我们是攻城狮啊!我们爱折腾啊 ...

  2. iView的使用【小白向】

    首先看这篇:构建Vue本地开发环境(现阶段还不知道怎么用CDN的方式做...) 安装iView(WindowsPowershell或cmd下用cnpm) 编辑上一篇博客创建的Vue工程 先到main. ...

  3. 理解Kubernetes(1):手工搭建Kubernetes测试环境

    系列文章: 1. 手工搭建环境 1. 基础环境准备 准备 3个Ubuntu节点,操作系统版本为 16.04,并做好以下配置: 系统升级 设置 /etc/hosts 文件,保持一致 设置从 0 节点上无 ...

  4. Qt编写QUI皮肤生成器

    用Qt写项目写多了,为了满足不同客户的需求,需要定制不同样式的界面,QUI皮肤生成器应运而生.思考这个工具的架构花了一年时间,如何从复杂的配色方案中提取出共性,然后将共性转为具体的QSS文件.思考架构 ...

  5. Git详解之六:Git工具

    Git 工具 现在,你已经学习了管理或者维护 Git 仓库,实现代码控制所需的大多数日常命令和工作流程.你已经完成了跟踪和提交文件的基本任务,并且发挥了暂存区和轻量级的特性分支及合并的威力.(伯乐在线 ...

  6. thinkphp 官方文件执行引入流程

    官方手册上的执行流程图: 系统流程 用户URL请求 调用应用入口文件(通常是网站的index.php) 载入框架入口文件(ThinkPHP.php) 记录初始运行时间和内存开销 系统常量判断及定义 载 ...

  7. Python爬取视频(其实是一篇福利)

    窗外下着小雨,作为单身程序员的我逛着逛着发现一篇好东西,来自知乎 你都用 Python 来做什么?的第一个高亮答案. 到上面去看了看,地址都是明文的,得,赶紧开始吧. 下载流式文件,requests库 ...

  8. VS2015 查看类之间的继承关系

    ---恢复内容开始--- 1. 右击项目名称,单击"查看"菜单下的"查看类图"菜单: 2.生成的类图如下:

  9. Micropython教程之TPYBoardv102 DIY蓝牙智能小车实例

    1.实验目的 1.学习在PC机系统中扩展简单I/O接口的方法. 2.进一步学习编制数据输出程序的设计方法. 3.学习蓝牙模块的接线方法及其工作原理. 4.学习L298N电机驱动板模块的接线方法. 5. ...

  10. 第十一章:Python の 网络编程基础(三)

    本課主題 多线程的创建和使用 消息队列的介绍 Python 操作 memached 和 redis 实战 本周作业 消息队列的介绍 对列是在内存中创建的,如果整个进程里的程序运行完毕之后会被清空,消息 ...