Blazor WebAssembly + Grpc Web=未来?

Blazor WebAssembly是什么

首先来说说WebAssembly是什么,WebAssembly是一个可以使C#,Java,Golang等静态强类型编程语言,运行在浏览器中的标准,浏览器厂商基于此标准实现执行引擎。

在实现了WebAssembly标准引擎之后,浏览器中可以执行由其他语言编译成的wasm模块。使用强类型编程语言的好处显而易见:

  • 可以选择更多的语言,编写前端逻辑

  • 静态编程语言编译成的字节码,相对于JS这种脚本语言执行效率更高

  • 可以使用静态编程语言生态中的强大类库

Blazor WebAssembly是dotnet版本的WebAssembly实现,微软将dotnet运行时编译成dotnet.wasm模块,我们的程序编译出来的dll文件运行在此模块上。

需要注意的是,Blazor WebAssembly是一个完完全全的前端框架,只是逻辑代码不再使用JS编写,而是使用C#编写。

Grpc Web是什么

Grpc是一种与语言无关的的高性能远程过程调用(RPC)框架。Grpc有以下优点

  • 现代高性能轻量级 RPC 框架。

  • 协定优先 API 开发,默认使用协议缓冲区,允许与语言无关的实现。

  • 可用于多种语言的工具,以生成强类型服务器和客户端。

  • 支持客户端、服务器和双向流式处理调用。

  • 使用 Protobuf 二进制序列化减少对网络的使用。

而Grpc Web是Grpc的前端实现版本,可以使浏览器应用直接与Grpc交互。

有了Grpc Web,我们可以直接在Blazor WebAssembly中调用Grpc Server,而不用再通过传统的Http请求方法调用。

代码演示

GrpcServer

首先需要新建一个Grpc Server

e2c11fcf1afe3dfd0122c62998a2ddbb.png

 然后为其引入 Grpc.AspNetCore.Web Nuget包,并开启grpc web

1ac0db1151424ad7562ea45b83cf87bb.png

app.UseGrpcWeb(); // Must be added between UseRouting and UseEndpoints// Configure the HTTP request pipeline.app.MapGrpcService<GreeterService>().EnableGrpcWeb();

之后我们需要为Grpc Server开启跨域设置,允许跨域访问

app.Use(async (context, next) =>{
    context.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
    context.Response.Headers.Add("Access-Control-Allow-Headers", "*");
    context.Response.Headers.Add("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS,HEAD,PATCH");
    context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
    context.Response.Headers.Add("Access-Control-Max-Age", "100000");
    context.Response.Headers.Add("Access-Control-Expose-Headers", "Grpc-Status,Grpc-Message,Grpc-Encoding,Grpc-Accept-Encoding");    
    if (context.Request.Method.ToUpper() == "OPTIONS")
    {        return;
    }    // Do work that can write to the Response.
    await next.Invoke();    // Do logging or other work that doesn't write to the Response.});

最终Program.cs的代码如下

using GrpcService2.Services;var builder = WebApplication.CreateBuilder(args);


builder.Services.AddGrpc();var app = builder.Build();
app.Use(async (context, next) =>{
    context.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
    context.Response.Headers.Add("Access-Control-Allow-Headers", "*");
    context.Response.Headers.Add("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS,HEAD,PATCH");
    context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
    context.Response.Headers.Add("Access-Control-Max-Age", "100000");
    context.Response.Headers.Add("Access-Control-Expose-Headers", "Grpc-Status,Grpc-Message,Grpc-Encoding,Grpc-Accept-Encoding");    if (context.Request.Method.ToUpper() == "OPTIONS")
    {        return;
    }    await next.Invoke();
});


app.UseGrpcWeb();
app.MapGrpcService<GreeterService>().EnableGrpcWeb();


app.MapGet("/", () => "Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");


app.Run();

Blazor WebAssembly

现在新建一个WebAssembly项目

21efc3d178192c9a0a23ffb53ffd937a.png

 为其引入以下nuget包

<ItemGroup>
    <PackageReference Include="Google.Protobuf" Version="3.20.1" />
    <PackageReference Include="Grpc.Net.Client" Version="2.46.0" />
    <PackageReference Include="Grpc.Net.Client.Web" Version="2.46.0" />
    <PackageReference Include="Grpc.Tools" Version="2.46.1">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
  </ItemGroup>

在其项目文件中包含进proto文件

<ItemGroup>
    <Protobuf Include="..\GrpcService2\Protos\*.proto" GrpcServices="Client" />
  </ItemGroup>

然后将GrpcClient注入容器

builder.Services.AddScoped(p =>
{
    var channel = GrpcChannel.ForAddress("https://localhost:7033/", new GrpcChannelOptions
    {
        HttpHandler = new GrpcWebHandler(new HttpClientHandler())
    });
    var client = new GrpcService2.Greeter.GreeterClient(channel);
    return client;
});

修改Index.razor,让其访问grpc server

@page "/"
@inject GrpcService2.Greeter.GreeterClient GreeterClient


<div>grpc web response @Message</div>


@code {
    public string Message { get; set; }
    protected override async Task OnInitializedAsync()
    {
        var reply = await GreeterClient.SayHelloAsync(new GrpcService2.HelloRequest { Name = "test" });
        Message = reply.Message;
    }
}

最终效果如下

f34437ded065558197854dafb7c5440c.png

可以看到整个请求/渲染过程,使用的是C#代码编写的逻辑,没用到js,原理是因为,blazor webassembly将我们的dotnet运行时,与我们的代码编译后的程序集,运行在了基于webassembly标准实现的浏览器引擎中。

77c3d5f94b72056c8bdd6425c95f5ec0.png

并且可以看到基于Grpc Web的请求响应体都使用的压缩过的二进制形式。效率相对更高

62addb7310160912fd4f83b4d361d89e.png 

daba12faafb07b781492c7b492017354.png

webassembly难道是未来?难道未来的某一天要和js say goodbye了吗?

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java + gRPC + grpc-gateway 的实践主要分为以下几个步骤: 1. 定义 proto 文件 在 proto 文件中定义需要调用的服务以及方法,同时指定请求和响应的数据类型。例如: ``` syntax = "proto3"; package example; service ExampleService { rpc ExampleMethod (ExampleRequest) returns (ExampleResponse) {} } message ExampleRequest { string example_field = 1; } message ExampleResponse { string example_field = 1; } ``` 2. 使用 protoc 编译 proto 文件 使用 protoc 编译 proto 文件,生成 Java 代码。例如: ``` protoc --java_out=./src/main/java ./example.proto ``` 3. 实现 gRPC 服务 在 Java 代码中实现定义的 gRPC 服务,例如: ``` public class ExampleServiceImpl extends ExampleServiceGrpc.ExampleServiceImplBase { @Override public void exampleMethod(ExampleRequest request, StreamObserver<ExampleResponse> responseObserver) { // 实现具体逻辑 ExampleResponse response = ExampleResponse.newBuilder().setExampleField("example").build(); responseObserver.onNext(response); responseObserver.onCompleted(); } } ``` 4. 启动 gRPC 服务器 使用 gRPC 提供的 ServerBuilder 构建 gRPC 服务器,并启动服务器。例如: ``` Server server = ServerBuilder.forPort(8080).addService(new ExampleServiceImpl()).build(); server.start(); ``` 5. 集成 grpc-gateway 使用 grpc-gateway 可以将 gRPC 服务转换为 HTTP/JSON API。在 proto 文件中添加以下内容: ``` import "google/api/annotations.proto"; service ExampleService { rpc ExampleMethod (ExampleRequest) returns (ExampleResponse) { option (google.api.http) = { post: "/example" body: "*" }; } } ``` 在 Java 代码中添加以下内容: ``` Server httpServer = ServerBuilder.forPort(8081).addService(new ExampleServiceImpl()).build(); httpServer.start(); String grpcServerUrl = "localhost:8080"; String httpServerUrl = "localhost:8081"; ProxyServerConfig proxyConfig = new ProxyServerConfig(grpcServerUrl, httpServerUrl, "/example"); HttpProxyServer httpProxyServer = new HttpProxyServer(proxyConfig); httpProxyServer.start(); ``` 6. 测试 使用 HTTP/JSON API 调用 gRPC 服务,例如: ``` POST http://localhost:8081/example Content-Type: application/json { "example_field": "example" } ``` 以上就是 Java + gRPC + grpc-gateway 的实践步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值