grpc

package
v0.0.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 12, 2024 License: MIT Imports: 7 Imported by: 0

README

Grpc Proxy Grpc

Simple implementation grpc agent grpc, used on the gateway

How to use it?

package main

import (
	"context"
	grpcProxy "github.com/lhdhtrc/microservice-go/proxy/grpc"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/encoding"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
	"net"
)

func main() {
	director := func(ctx context.Context, fullMethodName string) (context.Context, *grpc.ClientConn, error) {
		// 服务发现的服务列表
		endPoint := make(map[string][]string)

		// 根据fullMethodName获取可用节点
		nodes, ok := endPoint[fullMethodName]

		var cc *grpc.ClientConn
		err := status.Errorf(codes.Unimplemented, "Unknown method")

		if ok && len(nodes) != 0 {
			md, _ := metadata.FromIncomingContext(ctx)
			ctx = metadata.NewOutgoingContext(ctx, md.Copy())

			cc, err = grpc.DialContext(ctx, nodes[0])
		}

		return ctx, cc, err
	}

	listen, _ := net.Listen("tcp", 8080)
	server := grpc.NewServer(grpc.UnknownServiceHandler(grpcProxy.TransparentHandler(director)))
	_ = server.Serve(listen)
}

Finally

  • If you feel good, click on star.
  • If you have a good suggestion, please ask the issue.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultProxyOpt

func DefaultProxyOpt(cc *grpc.ClientConn) grpc.ServerOption

func NewProxy

func NewProxy(dst *grpc.ClientConn, opts ...grpc.ServerOption) *grpc.Server

func RegisterService

func RegisterService(server *grpc.Server, director StreamDirector, serviceName string, methodNames ...string)

RegisterService 注册代理服务

func TransparentHandler

func TransparentHandler(director StreamDirector) grpc.StreamHandler

TransparentHandler 提供一个透明代理的方式,将未知的服务请求转发到后端服务,返回处理程序可以作为grpc.UnknownServiceHandler使用

Types

type StreamDirector

type StreamDirector func(ctx context.Context, fullMethodName string) (context.Context, *grpc.ClientConn, error)

func DefaultDirector

func DefaultDirector(cc *grpc.ClientConn) StreamDirector

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL