MagicOnion Grpc ContractlessStandard
前言: MessagePack 序列化默认是标准的 StandardResolver ,如果希望DTO模型不再添加 [MessagePackObject(true)] 这样的注解(这样更普遍一些),那么需要在 Server端和 Client 端都要设置一下序列化的 Resolver,把默认的标准Resolver给替换掉。
以下给个例子:
1、DTO模型定义
public class SumRequest { public double Parm1 { get; set; } public double Parm2 { get; set; } } public class SumReply { public long Id { get; set; } public string Code { get; set; } public int Age { get; set; } public DateTime CreTime { get; set; } public double Amount { get; set; }// sum public decimal Price { get; set; } }
2、协议定义
public interface ISumTest: MagicOnion.IService<ISumTest> { MagicOnion.UnaryResult<SumReply> Sum(SumRequest req); }
3、Server 端协议的实现
public class SumTest : MagicOnion.Server.ServiceBase<ISumTest>, ISumTest { public MagicOnion.UnaryResult<SumReply> Sum(SumRequest req) { Console.WriteLine("hi, request coming"); return new MagicOnion.UnaryResult<SumReply>(new SumReply() { Age = 20, Amount = req.Parm1 + req.Parm2, CreTime = DateTime.Now.Local(), Id = 8888, Code = "中国人", Price = 99.8m }); } }
4、Server 服务开启
class Program { static void Main(string[] args) { try { var service = MagicOnionEngine.BuildServerServiceDefinition( new Assembly[] { typeof(Program).Assembly }, new MagicOnionOptions(false) { MagicOnionLogger = new MagicOnionLogToGrpcLogger(), SerializerOptions = MessagePackSerializerOptions.Standard.WithResolver( MessagePack.Resolvers.ContractlessStandardResolverAllowPrivate.Instance) }); Server server = new Server { Services = { service }, Ports = { new ServerPort("localhost", 5555, ServerCredentials.Insecure) } }; server.Start(); Console.WriteLine("localhost:5555 已开启"); } catch (Exception err) { Console.WriteLine(err.Message + Environment.NewLine + err.StackTrace); } Console.ReadLine(); } }
5、Client 调用
class Program { static void Main(string[] args) { var channel = new Channel("localhost", 5555, ChannelCredentials.Insecure); var client = MagicOnionClient.Create<ISumTest>(channel , MessagePack.MessagePackSerializerOptions.Standard.WithResolver( MessagePack.Resolvers.ContractlessStandardResolverAllowPrivate.Instance)); var rep = new SumRequest() { Parm1 = 123.456d, Parm2 = 456.789d }; var sum = client.Sum(rep).ResponseAsync.Result; } }
6、结果截图
posted on 2020-09-13 08:14 jonney_wang 阅读(249) 评论(0) 编辑 收藏 举报