1.依赖包
- Grpc.Net.Client
- Google.Protobuf
- Grpc.Tools
2.把相应的protos文件copy到项目文件目录下,重新编译项目,IDE会自动给你在项目文件中添加你的proto文件引用,如果没有可以自己手动添加。
<ItemGroup>
<Protobuf Include="Protos*.proto" GrpcServices="Client" Link="Protos\%(RecursiveDir)%(Filename)%(Extension)" />
<Protobuf Update="ProtosTest.proto">
<Link>ProtosTest.proto</Link>
</Protobuf>
</ItemGroup>
4.通过ioc的模式来调用grpc服务,配置Startup.ConfigureServices
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
services.AddGrpcClient<Test.TestClient>(options => {
options.Address = new Uri("http://localhost:5000");
});
5.直接注入客户端后调用。
public class DemoService : IDemo
{
private readonly Test.TestClient _TestClient;
public DemoService(Test.TestClient TestClient)
{
_TestClient = TestClient
}
public void Test()
{
//调用
TestClient.PrintAsync(new str
{
str = "hello"
});
}
}