通过C#学Proto.Actor模型》之Remote
Proto.Actor中提供了基于tcp/ip的通迅来实现Remote,可以通过其Remot实现对Actor的调用。
先来看一个极简单片的远程调用。
码友看码:
引用NuGet包
Proto.Actor
Proto.Remote
Proto.Serialization.Wire
共享库:
1 namespace P009_Lib 2 { 3 public class HelloRequest 4 { 5 public string Message 6 { 7 get; set; 8 } 9 } 10 public class HelloResponse 11 { 12 public string Message 13 { get; set; } 14 } 15 }
服务端:
1 using P009_Lib; 2 using Proto; 3 using Proto.Remote; 4 using Proto.Serialization.Wire; 5 using System; 6 7 using System.Threading; 8 using System.Threading.Tasks; 9 10 namespace P009_Server 11 { 12 class Program 13 { 14 static void Main(string[] args) 15 { 16 Console.Title = "服务端"; 17 Console.WriteLine("回车开始"); 18 Console.ReadLine(); 19 //设置序列化类型并注册 20 var wire = new WireSerializer(new[] { typeof(HelloRequest), typeof(HelloResponse) }); 21 Serialization.RegisterSerializer(wire, true); 22 23 var props = Actor.FromProducer(() => new HelloQuestActor()); 24 //注册一个为hello类别的 25 Remote.RegisterKnownKind("hello", props); 26 //服务端监控端口5001 27 Remote.Start("127.0.0.1", 5001); 28 Console.WriteLine("服务端开始……"); 29 Console.ReadLine(); 30 } 31 } 32 33 class HelloQuestActor : IActor 34 { 35 public Task ReceiveAsync(IContext context) 36 { 37 switch (context.Message) 38 { 39 case HelloRequest msg: 40 Console.WriteLine(msg.Message); 41 context.Respond(new HelloResponse 42 { 43 Message = $"回应:我是服务端【{DateTime.Now}】", 44 }); 45 break; 46 } 47 return Actor.Done; 48 } 49 } 50 }
客户端:
1 using P009_Lib; 2 using Proto; 3 using Proto.Remote; 4 using Proto.Serialization.Wire; 5 using System; 6 using System.Threading.Tasks; 7 8 namespace P009_Client 9 { 10 class Program 11 { 12 static void Main(string[] args) 13 { 14 15 Console.Title = "客户端"; 16 Console.WriteLine("回车开始"); 17 Console.ReadLine(); 18 //设置序列化类型并注册 19 var wire = new WireSerializer(new[] { typeof(HelloRequest), typeof(HelloResponse) }); 20 Serialization.RegisterSerializer(wire, true); 21 //设置自己监控端口5002 22 Remote.Start("127.0.0.1", 5002); 23 //连接服务端5001 24 var pid = Remote.SpawnNamedAsync("127.0.0.1:5001", "clientActor", "hello", TimeSpan.FromSeconds(50)).Result.Pid; 25 while (true) 26 { 27 var res = pid.RequestAsync<HelloResponse>(new HelloRequest { Message = $"请求:我是客户端 【{DateTime.Now}】" }).Result; 28 Console.WriteLine(res.Message); 29 Console.ReadLine(); 30 } 31 } 32 } 33 }
代码很简单,看注释就够了。
……
****欢迎关注我的asp.net core系统课程****
《asp.net core精要讲解》 https://ke.qq.com/course/265696
《asp.net core 3.0》 https://ke.qq.com/course/437517
《asp.net core项目实战》 https://ke.qq.com/course/291868
《基于.net core微服务》 https://ke.qq.com/course/299524
《asp.net core精要讲解》 https://ke.qq.com/course/265696
《asp.net core 3.0》 https://ke.qq.com/course/437517
《asp.net core项目实战》 https://ke.qq.com/course/291868
《基于.net core微服务》 https://ke.qq.com/course/299524