grpc: https://grpc.io/docs/languages/go/quickstart/

简单编写

server端

package main

import (
	"fmt"
	"net"
	"net/rpc"
)

// 定义类对象
type World struct {
}

// 绑定类方法
func (w *World) HelloWorld(name string, resp *string) error {
	*resp = name + " 你好!"
	return nil
}
func main() {
	// 1.注册rpc服务,绑定对象方法
	err := rpc.RegisterName("hello", new(World))
	if err != nil {
		fmt.Println("注册rpc服务失败", err)
		return
	}

	//2. 设置监听
	listener, err := net.Listen("tcp4", "127.0.0.1:8080")
	if err != nil {
		fmt.Println("net.Listen error", err)
		return
	}
	defer listener.Close()
	fmt.Println("开始监听:127.0.0.1:8080")
	//3. 建立链接

	conn, err := listener.Accept()
	if err != nil {
		fmt.Println("listener.Accept error:", err)
		return
	}
	defer conn.Close()
	fmt.Println("链接成功!")
	//4.绑定服务
	rpc.ServeConn(conn)
}

client端

package main

import (
	"fmt"
	"net/rpc"
)

func main() {
	// 1. 用rpc链接服务器
	client, err := rpc.Dial("tcp4", "127.0.0.1:8080")
	if err != nil {
		fmt.Println("dial error:", err)
		return
	}
	defer client.Close()
	// 2. 调用远程函数
	var reply string
	err = client.Call("hello.HelloWorld", "李白", &reply)
	if err != nil {
		fmt.Println("client.Call error", err)
		return
	}
	fmt.Println("replay from rpc:", reply)
}

封装

server.go

package main

import (
	"fmt"
	"net"
	"net/rpc/jsonrpc"
	"rpc_learn"
)

// 定义类对象
type World struct {
}

// 绑定类方法
func (w *World) HelloWorld(name string, resp *string) error {
	*resp = name + " 你好!"
	fmt.Println("调用了WORLD")
	return nil
}
func main() {
	// 1.注册rpc服务,绑定对象方法
	rpc_learn.RegisterRpcName(new(World))
	//2. 设置监听
	listener, err := net.Listen("tcp4", "127.0.0.1:8080")
	if err != nil {
		fmt.Println("net.Listen error", err)
		return
	}
	defer listener.Close()
	fmt.Println("开始监听:127.0.0.1:8080")
	//3. 建立链接

	conn, err := listener.Accept()
	if err != nil {
		fmt.Println("listener.Accept error:", err)
		return
	}
	defer conn.Close()
	fmt.Println("链接成功!")
	//4.绑定服务
	jsonrpc.ServeConn(conn)
}

client.go

package main

import (
	"fmt"
	"rpc_learn"
)

func main() {
	// 1. 用rpc链接服务器
	client := rpc_learn.InitClient("127.0.0.1:8080")
	defer client.(*rpc_learn.MyClient).Close()
	// 2. 调用远程函数
	var reply string
	err := client.HelloWorld("meowrain", &reply)
	if err != nil {
		fmt.Println("error: ", err)
	}
	fmt.Println("replay from rpc:", reply)
}

myinterface.go

package rpc_learn

import (
	"fmt"
	"net/rpc"
	"net/rpc/jsonrpc"
)

type MyInterface interface {
	HelloWorld(string, *string) error
}

func RegisterRpcName(i MyInterface) {
	err := rpc.RegisterName("hello", i)
	if err != nil {
		fmt.Println("rpc.RegisterName error:", err)
		return
	}
}

type MyClient struct {
	c *rpc.Client
}

func InitClient(addr string) MyInterface {
	conn, err := jsonrpc.Dial("tcp", addr)
	if err != nil {
		fmt.Println("jsonrpc.Dial error: ", err)
		return nil
	}
	var myclient MyClient = MyClient{
		c: conn,
	}
	return &myclient
}
func (myclient *MyClient) HelloWorld(name string, resp *string) error {
	err := myclient.c.Call("hello.HelloWorld", name, resp)
	if err != nil {
		return err
	}
	return nil
}
func (myclient *MyClient) Close() {
	myclient.c.Close()
}

protobuf

https://protobuf.com.cn/programming-guides/proto3/

例子:

syntax = "proto3";

package pb;
option go_package = ".";

message Student {
    int32 age = 1;
    string name = 2;
};
message People {
    string name = 1;
}
service bj38 {
    rpc Say(People) returns (Student);
}

生成go代码:

protoc --go_out=:. --go-grpc_out=:. *.proto

image

tproto.pb.go

// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// 	protoc-gen-go v1.34.2
// 	protoc        v5.27.3
// source: tproto.proto

package pb

import (
	protoreflect "google.golang.org/protobuf/reflect/protoreflect"
	protoimpl "google.golang.org/protobuf/runtime/protoimpl"
	reflect "reflect"
	sync "sync"
)

const (
	// Verify that this generated code is sufficiently up-to-date.
	_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
	// Verify that runtime/protoimpl is sufficiently up-to-date.
	_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)

type Student struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields

	Age  int32  `protobuf:"varint,1,opt,name=age,proto3" json:"age,omitempty"`
	Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
}

func (x *Student) Reset() {
	*x = Student{}
	if protoimpl.UnsafeEnabled {
		mi := &file_tproto_proto_msgTypes[0]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}

func (x *Student) String() string {
	return protoimpl.X.MessageStringOf(x)
}

func (*Student) ProtoMessage() {}

func (x *Student) ProtoReflect() protoreflect.Message {
	mi := &file_tproto_proto_msgTypes[0]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}

// Deprecated: Use Student.ProtoReflect.Descriptor instead.
func (*Student) Descriptor() ([]byte, []int) {
	return file_tproto_proto_rawDescGZIP(), []int{0}
}

func (x *Student) GetAge() int32 {
	if x != nil {
		return x.Age
	}
	return 0
}

func (x *Student) GetName() string {
	if x != nil {
		return x.Name
	}
	return ""
}

type People struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields

	Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
}

func (x *People) Reset() {
	*x = People{}
	if protoimpl.UnsafeEnabled {
		mi := &file_tproto_proto_msgTypes[1]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}

func (x *People) String() string {
	return protoimpl.X.MessageStringOf(x)
}

func (*People) ProtoMessage() {}

func (x *People) ProtoReflect() protoreflect.Message {
	mi := &file_tproto_proto_msgTypes[1]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}

// Deprecated: Use People.ProtoReflect.Descriptor instead.
func (*People) Descriptor() ([]byte, []int) {
	return file_tproto_proto_rawDescGZIP(), []int{1}
}

func (x *People) GetName() string {
	if x != nil {
		return x.Name
	}
	return ""
}

var File_tproto_proto protoreflect.FileDescriptor

var file_tproto_proto_rawDesc = []byte{
	0x0a, 0x0c, 0x74, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x02,
	0x70, 0x62, 0x22, 0x2f, 0x0a, 0x07, 0x53, 0x74, 0x75, 0x64, 0x65, 0x6e, 0x74, 0x12, 0x10, 0x0a,
	0x03, 0x61, 0x67, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x03, 0x61, 0x67, 0x65, 0x12,
	0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e,
	0x61, 0x6d, 0x65, 0x22, 0x1c, 0x0a, 0x06, 0x50, 0x65, 0x6f, 0x70, 0x6c, 0x65, 0x12, 0x12, 0x0a,
	0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d,
	0x65, 0x32, 0x26, 0x0a, 0x04, 0x62, 0x6a, 0x33, 0x38, 0x12, 0x1e, 0x0a, 0x03, 0x53, 0x61, 0x79,
	0x12, 0x0a, 0x2e, 0x70, 0x62, 0x2e, 0x50, 0x65, 0x6f, 0x70, 0x6c, 0x65, 0x1a, 0x0b, 0x2e, 0x70,
	0x62, 0x2e, 0x53, 0x74, 0x75, 0x64, 0x65, 0x6e, 0x74, 0x42, 0x03, 0x5a, 0x01, 0x2e, 0x62, 0x06,
	0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}

var (
	file_tproto_proto_rawDescOnce sync.Once
	file_tproto_proto_rawDescData = file_tproto_proto_rawDesc
)

func file_tproto_proto_rawDescGZIP() []byte {
	file_tproto_proto_rawDescOnce.Do(func() {
		file_tproto_proto_rawDescData = protoimpl.X.CompressGZIP(file_tproto_proto_rawDescData)
	})
	return file_tproto_proto_rawDescData
}

var file_tproto_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_tproto_proto_goTypes = []any{
	(*Student)(nil), // 0: pb.Student
	(*People)(nil),  // 1: pb.People
}
var file_tproto_proto_depIdxs = []int32{
	1, // 0: pb.bj38.Say:input_type -> pb.People
	0, // 1: pb.bj38.Say:output_type -> pb.Student
	1, // [1:2] is the sub-list for method output_type
	0, // [0:1] is the sub-list for method input_type
	0, // [0:0] is the sub-list for extension type_name
	0, // [0:0] is the sub-list for extension extendee
	0, // [0:0] is the sub-list for field type_name
}

func init() { file_tproto_proto_init() }
func file_tproto_proto_init() {
	if File_tproto_proto != nil {
		return
	}
	if !protoimpl.UnsafeEnabled {
		file_tproto_proto_msgTypes[0].Exporter = func(v any, i int) any {
			switch v := v.(*Student); i {
			case 0:
				return &v.state
			case 1:
				return &v.sizeCache
			case 2:
				return &v.unknownFields
			default:
				return nil
			}
		}
		file_tproto_proto_msgTypes[1].Exporter = func(v any, i int) any {
			switch v := v.(*People); i {
			case 0:
				return &v.state
			case 1:
				return &v.sizeCache
			case 2:
				return &v.unknownFields
			default:
				return nil
			}
		}
	}
	type x struct{}
	out := protoimpl.TypeBuilder{
		File: protoimpl.DescBuilder{
			GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
			RawDescriptor: file_tproto_proto_rawDesc,
			NumEnums:      0,
			NumMessages:   2,
			NumExtensions: 0,
			NumServices:   1,
		},
		GoTypes:           file_tproto_proto_goTypes,
		DependencyIndexes: file_tproto_proto_depIdxs,
		MessageInfos:      file_tproto_proto_msgTypes,
	}.Build()
	File_tproto_proto = out.File
	file_tproto_proto_rawDesc = nil
	file_tproto_proto_goTypes = nil
	file_tproto_proto_depIdxs = nil
}

tproto_grpc.pb.go

// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.5.1
// - protoc             v5.27.3
// source: tproto.proto

package pb

import (
	context "context"
	grpc "google.golang.org/grpc"
	codes "google.golang.org/grpc/codes"
	status "google.golang.org/grpc/status"
)

// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.64.0 or later.
const _ = grpc.SupportPackageIsVersion9

const (
	Bj38_Say_FullMethodName = "/pb.bj38/Say"
)

// Bj38Client is the client API for Bj38 service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type Bj38Client interface {
	Say(ctx context.Context, in *People, opts ...grpc.CallOption) (*Student, error)
}

type bj38Client struct {
	cc grpc.ClientConnInterface
}

func NewBj38Client(cc grpc.ClientConnInterface) Bj38Client {
	return &bj38Client{cc}
}

func (c *bj38Client) Say(ctx context.Context, in *People, opts ...grpc.CallOption) (*Student, error) {
	cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
	out := new(Student)
	err := c.cc.Invoke(ctx, Bj38_Say_FullMethodName, in, out, cOpts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

// Bj38Server is the server API for Bj38 service.
// All implementations must embed UnimplementedBj38Server
// for forward compatibility.
type Bj38Server interface {
	Say(context.Context, *People) (*Student, error)
	mustEmbedUnimplementedBj38Server()
}

// UnimplementedBj38Server must be embedded to have
// forward compatible implementations.
//
// NOTE: this should be embedded by value instead of pointer to avoid a nil
// pointer dereference when methods are called.
type UnimplementedBj38Server struct{}

func (UnimplementedBj38Server) Say(context.Context, *People) (*Student, error) {
	return nil, status.Errorf(codes.Unimplemented, "method Say not implemented")
}
func (UnimplementedBj38Server) mustEmbedUnimplementedBj38Server() {}
func (UnimplementedBj38Server) testEmbeddedByValue()              {}

// UnsafeBj38Server may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to Bj38Server will
// result in compilation errors.
type UnsafeBj38Server interface {
	mustEmbedUnimplementedBj38Server()
}

func RegisterBj38Server(s grpc.ServiceRegistrar, srv Bj38Server) {
	// If the following call pancis, it indicates UnimplementedBj38Server was
	// embedded by pointer and is nil.  This will cause panics if an
	// unimplemented method is ever invoked, so we test this at initialization
	// time to prevent it from happening at runtime later due to I/O.
	if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
		t.testEmbeddedByValue()
	}
	s.RegisterService(&Bj38_ServiceDesc, srv)
}

func _Bj38_Say_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(People)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(Bj38Server).Say(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: Bj38_Say_FullMethodName,
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(Bj38Server).Say(ctx, req.(*People))
	}
	return interceptor(ctx, in, info, handler)
}

// Bj38_ServiceDesc is the grpc.ServiceDesc for Bj38 service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var Bj38_ServiceDesc = grpc.ServiceDesc{
	ServiceName: "pb.bj38",
	HandlerType: (*Bj38Server)(nil),
	Methods: []grpc.MethodDesc{
		{
			MethodName: "Say",
			Handler:    _Bj38_Say_Handler,
		},
	},
	Streams:  []grpc.StreamDesc{},
	Metadata: "tproto.proto",
}

然后我们编写相应得client和server
server.go

import (
	"context"
	"go_learn/pb"
	"log"
	"net"

	"google.golang.org/grpc"
)

// server 是 Bj38Server 接口的实现
type server struct {
	pb.UnimplementedBj38Server
}

func (s *server) Say(ctx context.Context, in *pb.People) (*pb.Student, error) {
	// 实现业务逻辑
	return &pb.Student{Name: "Hello, " + in.Name}, nil
}

func main() {
	lis, err := net.Listen("tcp", ":50051")
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	s := grpc.NewServer()
	pb.RegisterBj38Server(s, &server{})
	log.Printf("server listening at %v", lis.Addr())
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}

client.go

package main

import (
	"context"
	"go_learn/pb"
	"log"
	"time"

	"google.golang.org/grpc"
)

func main() {
	conn, err := grpc.NewClient("localhost:50051", grpc.WithInsecure())
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()

	client := pb.NewBj38Client(conn)

	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	// 调用 Say 方法
	response, err := client.Say(ctx, &pb.People{Name: "World"})
	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}
	log.Printf("Greeting: %s", response.GetName())
}

image

image