Table of Contents
3.2 服务端代码
3.3 客户端代码
0x03 下一步
Home Backend Development C#.Net Tutorial DotBPE.RPC quick start

DotBPE.RPC quick start

May 31, 2017 pm 02:37 PM

0x00 Introduction

DotBPE.RPC is an RPC written based on dotnet coreFramework, and its father, DotBPE, aims to implement an out-of-the-box microservice framework, but it is still not very interesting and is still in the stage of conception and experimentation. But anyway, RPC is the basis of microservices. , let’s talk about the implementation of RPC first. The default implementation of DotBPE.RPC underlying communication is based on DotNetty, which is the C# Netty implementation developed by the Microsoft Azure team. Of course, you can also replace it with other Sockets. Communication component. The default protocol name used by DotBPE.RPC is Amp, and the encoding and decoding use Google's Protobuf3, but these default implementations can be replaced.

Source code address: github.com/xuanye/dotbpe.git#.

##0x01 About Amp Protocol and Google Protobuf

Amp(A Message Protocol)

Amp(A Message Protocol), the Chinese name is

一Message Protocol is the message protocol implemented by DotBPE.RPC by default. In actual development, it is not necessary to understand how messages are encoded, decoded and transmitted, but understanding the protocol will help to further understand the framework. The basic structure of the protocol is shown in the figure below:

      0        1 2 3 4   5 6 7 8     9     10 11     12 13   <length>-14
+------------+----------+---------+------+-------+---------+------------+
| <ver> | <length> |  <seq>  |<type>|<serid>| <msgid> |   <data>   |
+------------+----------+---------+------+-------+---------+------------+</data></msgid></serid></type></seq></length></ver></length>
Copy after login
The default message header length of the Amp protocol is 14 bytes, excluding the extension header

The 0th bit: ver/argc // is the version number, for the time being, the default is 0
Digits 1-4: length // is the total length of the packet (including header length)
Digits 5-8: sequence // is the message sequence number, through which the sequence number corresponds to the request response
9th position: type // Message type, there are 5 current values, as follows:

Request = 1, Response = 2, Not

ify = 3,NotFound = 4, ERROR = 5Bits 10-11: serviceId//message ID ushort type
Bit 12-13: msgId//message ID ushort type
In the Amp protocol, serviceId identifies a type of request , similar to the module in the application, and msgId identifies the specific method in the module

followed by the actual data

Google Protobuf

Google Protocol Buffer(abbreviation Protobuf) is Google's internal mixed language data standard. Currently, there are more than 48,162 message format definitions and more than 12,183 .proto files in use. They are used in RPC systems and persistent data storage systems.

Protocol Buffers is a lightweight and efficient structured data storage format that can be used for structured data serialization, or serialization. It is suitable for data storage or RPC data exchange format. A language-independent, platform-independent, and extensible serialized structured data format that can be used in communication protocols, data storage and other fields. Currently,

API is provided in multiple languages, including C++, C#, GO, JAVA, PYTHON

In my previous blog, I used CSharp to write the Google Protobuf plug-in. Let’s introduce how to define the proto file and generate the code we need by writing a plug-in.

In DotBPE.RPC, I use protobuf as the service description file, and generate server and client proxy classes through customized plug-ins.

0x02

Quick Start

0. Prerequisite

Because DotBPE is developed based on dotnet core, you must already have dotnet core locally The development environment

uses github to host the code, so you must have
installed the git client Need to generate template code through protoc, so you must have installed the google protobuf command line tool

1. Download the sample program

In order to explain our quick start program, you need a sample code that can be run locally. Downloading the sample code I have written from github allows you to quickly build the program and avoid some tedious but necessary steps.

>$ # Clone the repository to get the example code:    
>$ git clone https://github.com/xuanye/dotbpe-sample.git  
>$ cd dotbpe-sample
Copy after login
Use VS2017 or VSCode to open the downloaded code.

The directory structure is as follows:
DotBPE.RPC quick start

If you use VS2017, it can automatically help you Restore, if you use VSCode, you need to run

dotnet restore to download the dependencies. After success, use dotnet build to compile and see the result: it looks perfect
DotBPE.RPC quick start

2. Run the program

Run Server

>$ cd HelloDotBPE.Server   
>$ dotnet run
Copy after login

Run Client

>$ cd HelloDotBPE.Client   
>$ dotnet run
Copy after login

Congratulations! Have used DotBPE.RPC to run a Server/Client application.

3. Let’s take a look at the code

3.1 Service description file proto

The first is the proto extension file in the DotBPE.RPC framework. All projects require this File, regarding how to extend proto, my blog has a more detailed introduction, so I won’t repeat it here

//dotbpe_option.proto 文件

syntax = "proto3";
package dotbpe;


option csharp_namespace = "DotBPE.ProtoBuf";

import "google/protobuf/descriptor.proto";

//扩展服务
extend google.protobuf.ServiceOptions {
  int32 service_id = 51001;
  bool disable_generic_service_client = 51003; //禁止生成客户端代码
  bool disable_generic_service_server = 51004; //禁止生成服务端代码
}
extend google.protobuf.MethodOptions {
  int32 message_id = 51002;
}

extend google.protobuf.FileOptions {
  bool disable_generic_services_client = 51003; //禁止生成客户端代码
  bool disable_generic_services_server = 51004; //禁止生成服务端代码
  bool generic_markdown_doc = 51005; //是否生成文档 本示例中无用
  bool generic_objectfactory = 51006; //是否生成objectfactory 本示例中无用
}
Copy after login

下面的服务描述文件 greeter.proto 才是真正的示例的服务描述文件:比较简单,定义一个Greeter Rpc服务,并定义一个Hello的方法

//greeter.proto
syntax = "proto3";
package dotbpe;

option csharp_namespace = "HelloDotBPE.Common";

// 引入扩展
import public "dotbpe_option.proto";

// 定义一个服务
service Greeter {
  option (service_id)= 100 ;//消息ID,全局必须唯一
  // Sends a greeting
  rpc Hello (HelloRequest) returns (HelloResponse) {
    option (message_id)= 1 ;//设定消息ID,同一服务内唯一
  }

}

// The request message containing the user&#39;s name.
message HelloRequest {
  string name = 1;
}
// The response message containing the greetings
message HelloResponse {
  string message = 1;
}
Copy after login

通过protoc工具生成模板代码,示例中的代码生成到了 HelloDotBPE.Common_g 目录下,本地可以运行shell命令的同学可以直接到
dotbpe-sample\script\generate 目录运行sh generate_hello.sh (windows下一般安装cgywin),不能运行的同学也可以在HelloDotBPE目录下,直接运行命令行

protoc -I=../protos --csharp_out=./HelloDotBPE.Common/_g/ --dotbpe_out=./HelloDotBPE.Common/_g/   ../protos/dotbpe_option.proto ../protos/greeter.proto  --plugin=protoc-gen-dotbpe=../../tool/protoc_plugin/Protobuf.Gen.exe
Copy after login

当然我还是建议大家安装以下cgywin运行环境,可以运行unix上的一些常用命令。同时在部署到正式环境的时候可以公用开发环境的一些脚本。

3.2 服务端代码

服务实现:

// 服务实现代码
public class GreeterImpl : GreeterBase 
{ 
   public override Task<HelloResponse> HelloAsync(HelloRequest request)
   {
        // 直接返回Hello Name
       return Task.FromResult(new HelloResponse() { Message = "Hello " + request.Name });
   }
}
Copy after login

服务端启动类

 public class Startup : IStartup
    {
       
        public void Configure(IAppBuilder app, IHostingEnvironment env)
        {
           
        }

        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddDotBPE(); // 添加DotBPE.RPC的核心依赖
            services.AddServiceActors<AmpMessage>(actors => {
                actors.Add<GreeterImpl>(); // 注册服务实现
            });

            return services.BuildServiceProvider();
        }
    }
Copy after login

启动服务端

   class Program
    {
        static void Main(string[] args)
        {
            Console.OutputEncoding = System.Text.Encoding.UTF8;

            //在控制台输出调试日志
            DotBPE.Rpc.Environment.SetLogger(new DotBPE.Rpc.Logging.ConsoleLogger());

            var host = new RpcHostBuilder()
                .UseServer("0.0.0.0:6201") //绑定本地端口6201
                .UseStartup<Startup>()
                .Build();

            host.StartAsync().Wait();

            Console.WriteLine("Press any key to quit!");
            Console.ReadKey();

            host.ShutdownAsync().Wait();

        }
    }
Copy after login

3.3 客户端代码

 class Program
    {
        static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;

            var client = AmpClient.Create("127.0.0.1:6201"); //建立链接通道
            var greeter = new GreeterClient(client); //客户端代理类
           
            while (true)
            {
                Console.WriteLine("input your name and press enter:");
                string name = Console.ReadLine();
                if ("bye".Equals(name))
                {
                    break;
                }
                try
                {
                    var request = new HelloRequest() { Name = name };
                    var result = greeter.HelloAsync(request).Result;                  
                    Console.WriteLine($"---------------receive form server:{result.Message}-----------");
                                    
                }
                catch (Exception ex)
                {
                    Console.WriteLine("发生错误:" + ex.Message);
                }
            }
            Console.WriteLine($"---------------close connection-----------");
            client.CloseAsync();
        }
    }
Copy after login

0x03 下一步

下一篇 我将详细讲述DotBPE.RPC中的主要类和调用关系,并介绍如何使用DotNetty实现RPC通信。
事实上我正在编写一个更加复杂的示例https://github.com/xuanye/PiggyMetrics.git,
这原是spring cloud的一个示例程序,我使用DotBPE进行改造,用示例描述DotBPE在真实场景中的应用。包括服务注册和发现,服务间调用,公开HttpApi,监控检查等功能,并通过实践进一步完善DotBPE。初步的功能已经实现,不过还没来的及写文档。该系列的后面将详细描述该系统的实现。

The above is the detailed content of DotBPE.RPC quick start. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1279
29
C# Tutorial
1257
24
Solution to the inability to connect to the RPC server and the inability to enter the desktop Solution to the inability to connect to the RPC server and the inability to enter the desktop Feb 18, 2024 am 10:34 AM

What should I do if the RPC server is unavailable and cannot be accessed on the desktop? In recent years, computers and the Internet have penetrated into every corner of our lives. As a technology for centralized computing and resource sharing, Remote Procedure Call (RPC) plays a vital role in network communication. However, sometimes we may encounter a situation where the RPC server is unavailable, resulting in the inability to enter the desktop. This article will describe some of the possible causes of this problem and provide solutions. First, we need to understand why the RPC server is unavailable. RPC server is a

Go language RPC framework inventory: List of five popular choices Go language RPC framework inventory: List of five popular choices Feb 27, 2024 pm 01:03 PM

With the development of Internet technology, distributed systems are used more and more widely, and Remote Procedure Call (RPC), as an important communication method in distributed systems, has also received more and more attention and applications. Among the many RPC frameworks, Go language, as a fast and efficient programming language, also has a rich selection of RPC frameworks. This article will take stock of the Go language RPC framework, introduce the five popular choices, and give specific code examples to help readers better understand and choose the RPC framework suitable for their own projects. 1.g

High-concurrency RPC service practice based on ThinkPHP6 and Swoole High-concurrency RPC service practice based on ThinkPHP6 and Swoole Oct 12, 2023 pm 03:12 PM

High concurrency RPC service practice introduction based on ThinkPHP6 and Swoole: In modern web application development, high concurrency is a very important issue. With the rapid development of the Internet and the increase in the number of users, the traditional Web architecture can no longer meet the demand for high concurrency. In order to solve this problem, we can use an RPC (remote procedure call)-based architecture to implement high-concurrency services. This article will introduce how to use ThinkPHP6 and Swoole to build a high-concurrency RPC service, and

High-performance RPC service developed using ThinkPHP6 and Swoole High-performance RPC service developed using ThinkPHP6 and Swoole Oct 12, 2023 am 10:18 AM

High-performance RPC service developed using ThinkPHP6 and Swoole With the rapid development of the Internet, cross-language remote procedure calls (RPC) play an important role in distributed systems. In the traditional RPC architecture, HTTP or TCP protocols are usually used for communication, but this method still needs to be improved in terms of performance and concurrency capabilities. In order to solve this problem, this article will introduce how to use ThinkPHP6 and Swoole to develop a high-performance RPC service. First, we will briefly introduce

How to implement RPC remote calling in PHP? How to implement RPC remote calling in PHP? May 11, 2023 pm 11:51 PM

With the rapid development of the Internet and the widespread application of cloud computing technology, distributed systems and microservice architectures are becoming more and more common. In this context, remote procedure call (RPC) has become a common technical means. RPC can enable different services to be called remotely on the network, thereby realizing interconnection operations between different services and improving code reusability and scalability. As a widely used Web development language, PHP is also commonly used in the development of various distributed systems. So, how to implement RPC remote debugging in PHP?

Golang development: using RPC to achieve cross-process communication Golang development: using RPC to achieve cross-process communication Sep 21, 2023 pm 03:26 PM

Golang development: Using RPC to achieve cross-process communication requires specific code examples 1. Introduction RPCRPC (RemoteProcedureCall) is a remote procedure call protocol, which allows the client to call functions or methods of the server program located on the remote computer, just like Same as calling local functions. RPC can be implemented using different network protocols, such as TCP, HTTP, etc. In distributed systems, RPC is an important communication mechanism, often used for communication across processes or across network nodes.

RPC service based on ThinkPHP6 and Swoole to implement data encryption and decryption RPC service based on ThinkPHP6 and Swoole to implement data encryption and decryption Oct 12, 2023 pm 02:57 PM

Implementing data encryption and decryption using RPC services based on ThinkPHP6 and Swoole As network security issues become increasingly prominent, the need for data encryption and decryption becomes more and more important. In web applications, communication between different servers can be achieved through RPC (remote procedure call) technology, and data encryption and decryption can ensure the security of data during the communication process. This article will introduce how to implement an RPC service based on ThinkPHP6 and Swoole framework, and add data encryption and decryption to it.

Using Swoole to implement a high-performance RPC framework Using Swoole to implement a high-performance RPC framework Aug 09, 2023 am 09:57 AM

Using Swoole to implement high-performance RPC framework With the rapid development of the Internet, RPC (remote procedure call) has become an important part of building distributed systems. However, traditional RPC frameworks often perform poorly in high-concurrency scenarios and have long response times, affecting system performance. Swoole, as a high-performance asynchronous network communication engine written in pure C language, has coroutine support and high concurrency processing capabilities, providing strong support for us to implement a high-performance RPC framework. This article will introduce how to use Swoo

See all articles