dart grpc 试用

主要是体验下dart grpc 的集成试用,grpc 对于dart 的支持也是基于了插件生成代码,然后我们可以基于生成的代码创建实现,client 进行调用

参考项目

代码来自官方示例

  • 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 helloworld;
 
// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}
 
// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}
 
// The response message containing the greetings
message HelloReply {
  string message = 1;
} 
  • 生成代码
    注意需要安装protoc 以及 dart grpc 扩展dart pub global activate protoc_plugin
 
protoc --dart_out=grpc:lib/src/generated -Iprotos protos/helloworld.proto
  • 效果

 

  • server 实现
    server.dart
 
import 'package:grpc/grpc.dart';
import 'package:helloworld/src/generated/helloworld.pbgrpc.dart';
 
// 实现
class GreeterService extends GreeterServiceBase {
  @override
  Future<HelloReply> sayHello(ServiceCall call, HelloRequest request) async {
    return HelloReply()..message = 'Hello, ${request.name}!';
  }
}
// 服务启动
Future<void> main(List<String> args) async {
  final server = Server.create(
    services: [GreeterService()],
    codecRegistry: CodecRegistry(codecs: const [GzipCodec(), IdentityCodec()]),
  );
  await server.serve(port: 50051);
  print('Server listening on port ${server.port}...');
}
  • client 实现
    client.dart
 
import 'package:grpc/grpc.dart';
import 'package:helloworld/src/generated/helloworld.pbgrpc.dart';
 
Future<void> main(List<String> args) async {
  // channel  创建
  final channel = ClientChannel(
    'localhost',
    port: 50051,
    options: ChannelOptions(
      credentials: ChannelCredentials.insecure(),
      codecRegistry:
          CodecRegistry(codecs: const [GzipCodec(), IdentityCodec()]),
    ),
  );
  // client stub
  final stub = GreeterClient(channel);
 
  final name = args.isNotEmpty ? args[0] : 'world';
 
  try {
    final response = await stub.sayHello(
      HelloRequest()..name = name,
      options: CallOptions(compression: const GzipCodec()),
    );
    print('Greeter client received: ${response.message}');
  } catch (e) {
    print('Caught error: $e');
  }
  await channel.shutdown();
}

说明

对于一些业务系统(比如基于flutter 开发的桌面应用基于dart grpc 进行数据通信也是一个不错的选择),当然buf 基于protobuf 的connect
协议也是一个不错的选择

参考资料

https://connectrpc.com/
https://github.com/grpc/grpc-dart
https://pub.dev/packages/grpc/install
https://buf.build/
https://grpc.io/docs/languages/dart/quickstart/
https://github.com/grpc/grpc-web

posted on 2023-10-20 10:57  荣锋亮  阅读(82)  评论(0编辑  收藏  举报

导航