Rpc簡單入門


      RPC這個概念大家都應該很熟悉了,這里不在累述了;使用場景可以參考這篇,本篇主要分享下ThriftGrpc.Net Core環境下使用入門。Thirft或者Grps 都支持跨語言、跨平台的Rpc框架。編寫IDL文件通過其強大的代碼生成引擎生成C#代碼,然后編寫服務器端和客戶端代碼進行交互。

  •  Thrift 入門demo

創建兩個控制台程序(client和service端)和一個類庫,三個項目都分別安裝thrift包;

Install-Package apache-thrift-netcore -Version 0.9.3.2;

簡單實現一個遠程調用用戶中心服務,獲取用戶信息;

項目截圖如下:

步驟1:下載Thrift放到指定盤;

  我的是放到E:\Thrift下。

步驟2:編寫.thrift文件 

namespace csharp Thrift.Contract

service UserService{
   User Get(1:i32 id)
}

struct User
{
    1: required i64 Id;
    2: required string Name;
    4: optional string Remark;
}

步驟3:生成對應的代碼 

 執行命令:thrift.exe --gen csharp UserServices.thrift

會看到生成的文件

把生成的項目拷到Thrift.Contract項目下; 並新增一個實現類

  public class UserServiceImpl : Iface
    {
        public User Get(int id)
        {
            return new User
            {
                 Id=1,
                 Name="成天",
                 Remark="熱愛編程,熱愛分享,熱愛..."
            };
        }
    }

步驟4:編寫服務端 

  private const int port = 8800;
        static void Main(string[] args)
        {
          
            Console.WriteLine("用戶中心RPC Server已啟動...");
            TServerTransport transport = new TServerSocket(port);
            var processor = new UserService.Processor(new UserServiceImpl());
            TServer server = new TThreadedServer(processor, transport);

            //如果多個服務實現的話,也可以這樣啟動;
            //var processor2 = new Manulife.DNC.MSAD.Contracts.PayoutService.Processor(new PayoutServiceImpl());
            //var processorMulti = new Thrift.Protocol.TMultiplexedProcessor();
            //processorMulti.RegisterProcessor("Service1", processor1);
            //processorMulti.RegisterProcessor("Service2", processor2);
            //TServer server = new TThreadedServer(processorMulti, transport);
            // lanuch
            server.Serve();
        }

步驟5:編寫客戶端

  static void Main(string[] args)
        {
            TTransport transport = new TSocket("localhost", 8800);
            TProtocol protocol = new TBinaryProtocol(transport);

            var client = new UserService.Client(protocol);
            transport.Open();

            var userResult = client.Get(1);

            Console.Write($"rpc->UserResult:{userResult.Name},{userResult.Remark}" );

            transport.Close();

            Console.ReadKey();
        }

然后運行服務端和客戶端調用結果如下圖:

  • Grpc 入門demo

Grpc代碼工具通過nuget安裝Grpc.Tools獲取,把grpc_csharp_pluginprotoc放到對應的盤中;代碼實現與thrift一樣的需求;項目分別安裝Grpc包

  • Install-Package Google.Protobuf -Version 3.6.0
  • Install-Package Grpc -Version 1.13.1

步驟1:編寫.proto文件 

syntax = "proto3";

option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";

package Grpc.Contract;

 
service UserService {
   rpc GetUser (GetUserRequest) returns (GetUserResponse) {}
}

 
message GetUserRequest {
  int32 Id = 1;
}

 
message GetUserResponse {
     int64 Id=1;
     string Name=2;
     string Remark=3;
}

步驟2:生成對應的代碼

執行命令:protoc.exe -I=. --csharp_out=. --grpc_out=. --plugin=protoc-gen-grpc=grpc_csharp_plugin.exe UserServices.proto

然后把生成的代碼拷貝到Grpc.Contract;並新增一個實現類

  public class UserServiceImpl: UserService.UserServiceBase
    {

        public override Task<GetUserResponse> GetUser(GetUserRequest request, ServerCallContext context)
        {
            return Task.FromResult(new GetUserResponse {
                Id = 1,
                Name = "成天",
                Remark = "熱愛編程,熱愛分享,熱愛..."
            });
        }
    }

步驟3:編寫服務端

  const int port = 50051;
        static void Main(string[] args)
        {

            Console.WriteLine("用戶中心RPC Server已啟動...");
            Server server = new Server
            {
                Services = { UserService.BindService(new UserServiceImpl()) },
                Ports = { new ServerPort("localhost", port, ServerCredentials.Insecure) }
            };

            server.Start();
            Console.ReadKey();
        }

步驟4:編寫客戶端

    Channel channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure);

            var client = new UserService.UserServiceClient(channel);

            var userResult = client.GetUser(new GetUserRequest{ Id = 1});
            Console.Write($"rpc->UserResult:{userResult.Name},{userResult.Remark}");
        
            channel.ShutdownAsync().Wait();
            Console.ReadKey();

然后運行服務端和客戶端調用結果如下圖:

到此這兩種流行的rpc框架使用介紹完畢,是不是很簡單。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM