簡體   English   中英

如何使用 Envoy 和 Grpc_web 連接 go grpc 服務器和 dart grpc 客戶端

[英]How to connect go grpc server with dart grpc client using Envoy and Grpc_web

我是 grpc_web 和特使的新手。

請幫我設置以下內容,

  1. GRPC_Go 服務器作為 docker 容器在 ec2 實例上運行
  2. Dart web 客戶端正在本地 pc 上運行
  3. 需要從 dart web app 向 grpc_go 服務器發起 grpc 調用請求
  4. 使用特使代理轉發請求。 Envoy 代理在同一 ec2 實例中作為容器運行

我收到以下錯誤“響應:null,預告片:{access-control-allow-credentials:true,access-control-allow-origin: http://127.0.0.1:9000 ,變化:Origin})”。

Grpc_Go:

package main

import (
"context"
"flag"
"fmt"
"log"
"net"

"google.golang.org/grpc"
pb "google.golang.org/grpc/examples/helloworld/helloworld"
)

var (
  port = flag.Int("port", 50051, "The server port")
)

// server is used to implement helloworld.GreeterServer.
type server struct {
   pb.UnimplementedGreeterServer
}

// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
   log.Printf("Received: %v", in.GetName())
   return &pb.HelloReply{Message: "Hello " + in.GetName()}, nil
}

func (s *server) SayHelloAgain(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, 
error) 
{
   return &pb.HelloReply{Message: "Hello again " + in.GetName()}, nil
}

func main() {
flag.Parse()
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
if err != nil {
    log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
pb.RegisterGreeterServer(s, &server{})
log.Printf("server listening at %v", lis.Addr())
if err := s.Serve(lis); err != nil {
    log.Fatalf("failed to serve: %v", err)
 }
} 

GRPC_dart_client:


import 'package:grpc/grpc_web.dart';
import 'package:grpc_web/app.dart';
import 'package:grpc_web/src/generated/echo.pbgrpc.dart';

void main() {
  final channel = GrpcWebClientChannel.xhr(Uri.parse('http://ec2-ip:8080'));
  final service = EchoServiceClient(channel);
  final app = EchoApp(service);

  final button = querySelector('#send') as ButtonElement;
  button.onClick.listen((e) async {
    final msg = querySelector('#msg') as TextInputElement;
    final value = msg.value!.trim();
    msg.value = '';

    if (value.isEmpty) return;

    if (value.indexOf(' ') > 0) {
      final countStr = value.substring(0, value.indexOf(' '));
      final count = int.tryParse(countStr);

      if (count != null) {
        app.repeatEcho(value.substring(value.indexOf(' ') + 1), count);
      } else {
        app.echo(value);
      }
    } else {
      app.echo(value);
    }
  });
}

特使.yaml:

  access_log_path: /tmp/admin_access.log
  address:
    socket_address: { address: 0.0.0.0, port_value: 9901 }

static_resources:
  listeners:
  - name: listener_0
    address:
      socket_address: { address: 0.0.0.0, port_value: 8080 }
    filter_chains:
    - filters:
      - name: envoy.filters.network.http_connection_manager
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
          codec_type: auto
          stat_prefix: ingress_http
          route_config:
            name: local_route
            virtual_hosts:
            - name: local_service
              domains: ["*"]
              routes:
              - match: { prefix: "/" }
                route:
                  cluster: echo_service
                  timeout: 0s
                  max_stream_duration:
                    grpc_timeout_header_max: 0s
              cors:
                allow_origin_string_match:
                - prefix: "*"
                allow_methods: GET, PUT, DELETE, POST, OPTIONS
                allow_headers: keep-alive,user-agent,cache-control,content-type,content-transfer-encoding,custom-header-1,x-accept-content-transfer-encoding,x-accept-response-streaming,x-user-agent,x-grpc-web,grpc-timeout
                max_age: "1728000"
                expose_headers: custom-header-1,grpc-status,grpc-message
          http_filters:
          - name: envoy.filters.http.grpc_web
          - name: envoy.filters.http.cors
          - name: envoy.filters.http.router
  clusters:
  - name: echo_service
    connect_timeout: 0.25s
    type: logical_dns
    http2_protocol_options: {}
    lb_policy: round_robin
    load_assignment:
      cluster_name: cluster_0
      endpoints:
        - lb_endpoints:
            - endpoint:
                address:
                  socket_address:
                    address: app
                    port_value: 50051

grpc_go_docker_file:


# Install git.
# Git is required for fetching the dependencies.
RUN apk update && apk add --no-cache git
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .

# Start a new stage from scratch
FROM alpine:latest
RUN apk --no-cache add ca-certificates

WORKDIR /root/

# Copy the Pre-built binary file from the previous stage. Observe we also copied the .env file
COPY --from=builder /app/main .
# Expose port 50051 to the outside world
EXPOSE 50051

CMD ["./main"] 

特使碼頭工人:


COPY envoy.yaml /etc/envoy/envoy.yaml

CMD /usr/local/bin/envoy -c /etc/envoy/envoy.yaml -l trace --log-path /tmp/envoy_info.log

我堅持了兩天多,請幫助我。 提前致謝

謝謝大家,謝謝你們的回復。

我用 ec2 實例的 IP 解決了這個問題。

clusters:
  - name: echo_service
    connect_timeout: 0.25s
    type: logical_dns
    http2_protocol_options: {}
    lb_policy: round_robin
    load_assignment:
      cluster_name: cluster_0
      endpoints:
        - lb_endpoints:
            - endpoint:
                address:
                  socket_address:
                    address: app
                    port_value: 50051

我沒有使用 envoy.yaml 中的容器“地址:app”(app 是容器名稱),而是使用了 ec2 實例和容器端口的 ip,現在 envoy 正在將請求轉發到服務器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM