RPC
server.go
package main
import (
"fmt"
"log"
"net/http"
"net/rpc"
)
type Calc struct{}
type Params struct{
A int
B int
}
// 1.方法名首字母必须要大写
// 2.方法的第一个参数是接收参数,第二个参数是返回给客户端的参数,必须是指针类型
// 3.方法必须有一个返回值error
func (c *Calc) Sum(p Params, res *int) error {
*res = p.A + p.B
return nil
}
func main() {
calc := new(Calc)
// 注册服务
rpc.Register(calc)
// 把服务绑定到http协议上
rpc.HandleHTTP()
// 监听服务
fmt.Println("listen 8090...")
if err := http.ListenAndServe(":8090", nil); err != nil {
log.Fatal(err)
}
}
client.go
package main
import (
"log"
"net/rpc"
"fmt"
)
type Params struct{
A int
B int
}
func main() {
client, err := rpc.DialHTTP("tcp", "127.0.0.1:8090")
if err != nil {
log.Fatal(err)
}
var result int
client.Call("Calc.Sum", Params{
A: 3,
B: 26,
}, &result)
fmt.Printf("result:%v\n", result)
}
jsonrpc
server.go
package main
import (
"fmt"
"log"
"net"
"net/rpc"
"net/rpc/jsonrpc"
)
type Calc struct{}
type Params struct{
A int
B int
}
// 1.方法名首字母必须要大写
// 2.方法的第一个参数是接收参数,第二个参数是返回给客户端的参数,必须是指针类型
// 3.方法必须有一个返回值error
func (c *Calc) Sum(p Params, res *int) error {
*res = p.A + p.B
return nil
}
func main() {
calc := new(Calc)
// 注册服务
rpc.Register(calc)
listen, err := net.Listen("tcp", ":8090")
fmt.Println("listen :8090...")
if err != nil {
log.Fatal(err)
}
for {
conn, err := listen.Accept()
if err != nil {
continue
}
go func(conn net.Conn) {
fmt.Println("new client connect", conn.RemoteAddr())
jsonrpc.ServeConn(conn)
}(conn)
}
}
client.go
package main
import (
"fmt"
"log"
"net/rpc/jsonrpc"
)
type Params struct{
A int
B int
}
func main() {
client, err := jsonrpc.Dial("tcp", "127.0.0.1:8090")
if err != nil {
log.Fatal(err)
}
var result int
client.Call("Calc.Sum", Params{
A: 3,
B: 26,
}, &result)
fmt.Printf("result:%v\n", result)
}
gRPC
中文文档地址 doc.oschina.net/grpc?t=6013…
user.proto
// 定义proto的版本
syntax = "proto3";
// 新版本语法
// pb指的是放在哪个文件夹里, 文件夹会自动生成
// proto指的是生成的包名
option go_package = "pb;proto";
// 定义客户端请求的数据格式
message UserRequest {
// 定义请求参数
string name = 1;
}
// 定义服务端响应的数据格式
message UserResponse {
// 定义响应参数
int32 id = 1;
string name = 2;
int32 age = 3;
repeated string hobby = 4;
}
// 定义开放调用的服务, 类似于接口
service UserInfoService {
// 相当于接口内的方法
// 定义请求参数为UserRequest, 响应参数为UserResponse
rpc GetUserInfo(UserRequest) returns (UserResponse){}
}
生成 xx.pb.go 文件
protoc -I . --go_out=plugins=grpc:. ./user.proto
生成的 xx.pb.go 文件
// 定义proto的版本
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.25.0
// protoc v3.14.0
// source: user.proto
package proto
import (
context "context"
proto "github.com/golang/protobuf/proto"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
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)
)
// This is a compile-time assertion that a sufficiently up-to-date version
// of the legacy proto package is being used.
const _ = proto.ProtoPackageIsVersion4
// 定义客户端请求的数据格式
type UserRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// 定义请求参数
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
}
func (x *UserRequest) Reset() {
*x = UserRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_user_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *UserRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UserRequest) ProtoMessage() {}
func (x *UserRequest) ProtoReflect() protoreflect.Message {
mi := &file_user_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 UserRequest.ProtoReflect.Descriptor instead.
func (*UserRequest) Descriptor() ([]byte, []int) {
return file_user_proto_rawDescGZIP(), []int{0}
}
func (x *UserRequest) GetName() string {
if x != nil {
return x.Name
}
return ""
}
// 定义服务端响应的数据格式
type UserResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// 定义响应参数
Id int32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
Age int32 `protobuf:"varint,3,opt,name=age,proto3" json:"age,omitempty"`
Hobby []string `protobuf:"bytes,4,rep,name=hobby,proto3" json:"hobby,omitempty"`
}
func (x *UserResponse) Reset() {
*x = UserResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_user_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *UserResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UserResponse) ProtoMessage() {}
func (x *UserResponse) ProtoReflect() protoreflect.Message {
mi := &file_user_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 UserResponse.ProtoReflect.Descriptor instead.
func (*UserResponse) Descriptor() ([]byte, []int) {
return file_user_proto_rawDescGZIP(), []int{1}
}
func (x *UserResponse) GetId() int32 {
if x != nil {
return x.Id
}
return 0
}
func (x *UserResponse) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *UserResponse) GetAge() int32 {
if x != nil {
return x.Age
}
return 0
}
func (x *UserResponse) GetHobby() []string {
if x != nil {
return x.Hobby
}
return nil
}
var File_user_proto protoreflect.FileDescriptor
var file_user_proto_rawDesc = []byte{
0x0a, 0x0a, 0x75, 0x73, 0x65, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x21, 0x0a, 0x0b,
0x55, 0x73, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x6e,
0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x22,
0x5a, 0x0a, 0x0c, 0x55, 0x73, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12,
0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x02, 0x69, 0x64, 0x12,
0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e,
0x61, 0x6d, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x61, 0x67, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05,
0x52, 0x03, 0x61, 0x67, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x68, 0x6f, 0x62, 0x62, 0x79, 0x18, 0x04,
0x20, 0x03, 0x28, 0x09, 0x52, 0x05, 0x68, 0x6f, 0x62, 0x62, 0x79, 0x32, 0x3f, 0x0a, 0x0f, 0x55,
0x73, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x2c,
0x0a, 0x0b, 0x47, 0x65, 0x74, 0x55, 0x73, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x0c, 0x2e,
0x55, 0x73, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x0d, 0x2e, 0x55, 0x73,
0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x42, 0x0a, 0x5a, 0x08,
0x70, 0x62, 0x3b, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_user_proto_rawDescOnce sync.Once
file_user_proto_rawDescData = file_user_proto_rawDesc
)
func file_user_proto_rawDescGZIP() []byte {
file_user_proto_rawDescOnce.Do(func() {
file_user_proto_rawDescData = protoimpl.X.CompressGZIP(file_user_proto_rawDescData)
})
return file_user_proto_rawDescData
}
var file_user_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_user_proto_goTypes = []interface{}{
(*UserRequest)(nil), // 0: UserRequest
(*UserResponse)(nil), // 1: UserResponse
}
var file_user_proto_depIdxs = []int32{
0, // 0: UserInfoService.GetUserInfo:input_type -> UserRequest
1, // 1: UserInfoService.GetUserInfo:output_type -> UserResponse
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_user_proto_init() }
func file_user_proto_init() {
if File_user_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_user_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*UserRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_user_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*UserResponse); 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_user_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_user_proto_goTypes,
DependencyIndexes: file_user_proto_depIdxs,
MessageInfos: file_user_proto_msgTypes,
}.Build()
File_user_proto = out.File
file_user_proto_rawDesc = nil
file_user_proto_goTypes = nil
file_user_proto_depIdxs = nil
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConnInterface
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion6
// UserInfoServiceClient is the client API for UserInfoService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type UserInfoServiceClient interface {
// 相当于接口内的方法
// 定义请求参数为UserRequest, 响应参数为UserResponse
GetUserInfo(ctx context.Context, in *UserRequest, opts ...grpc.CallOption) (*UserResponse, error)
}
type userInfoServiceClient struct {
cc grpc.ClientConnInterface
}
func NewUserInfoServiceClient(cc grpc.ClientConnInterface) UserInfoServiceClient {
return &userInfoServiceClient{cc}
}
func (c *userInfoServiceClient) GetUserInfo(ctx context.Context, in *UserRequest, opts ...grpc.CallOption) (*UserResponse, error) {
out := new(UserResponse)
err := c.cc.Invoke(ctx, "/UserInfoService/GetUserInfo", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// UserInfoServiceServer is the server API for UserInfoService service.
type UserInfoServiceServer interface {
// 相当于接口内的方法
// 定义请求参数为UserRequest, 响应参数为UserResponse
GetUserInfo(context.Context, *UserRequest) (*UserResponse, error)
}
// UnimplementedUserInfoServiceServer can be embedded to have forward compatible implementations.
type UnimplementedUserInfoServiceServer struct {
}
func (*UnimplementedUserInfoServiceServer) GetUserInfo(context.Context, *UserRequest) (*UserResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetUserInfo not implemented")
}
func RegisterUserInfoServiceServer(s *grpc.Server, srv UserInfoServiceServer) {
s.RegisterService(&_UserInfoService_serviceDesc, srv)
}
func _UserInfoService_GetUserInfo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(UserRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(UserInfoServiceServer).GetUserInfo(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/UserInfoService/GetUserInfo",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UserInfoServiceServer).GetUserInfo(ctx, req.(*UserRequest))
}
return interceptor(ctx, in, info, handler)
}
var _UserInfoService_serviceDesc = grpc.ServiceDesc{
ServiceName: "UserInfoService",
HandlerType: (*UserInfoServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "GetUserInfo",
Handler: _UserInfoService_GetUserInfo_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "user.proto",
}
server.go
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"log"
"net"
)
import pb "awesomeProject2/pb"
// 需要实现 user.pb.go中的UserInfoServiceServer接口
type UserInfoService struct {}
var u UserInfoService
// 这里实现了 user.pb.go中的UserInfoServiceServer接口
func (s *UserInfoService) GetUserInfo(ctx context.Context, req *pb.UserRequest) (resp *pb.UserResponse, err error) {
name := req.Name
resp = &pb.UserResponse{
Id: 1001,
Name: name,
Age: 23,
Hobby: []string{"乒乓球", "游戏", "写代码"},
}
err = nil
return
}
func main() {
// 监听
listen, err := net.Listen("tcp", ":8090")
fmt.Println("listen :8090...")
if err != nil {
fmt.Printf("监听失败: %v\n", err)
}
// 实例化gRPC
s := grpc.NewServer()
// 在gRPC上注册服务
pb.RegisterUserInfoServiceServer(s, &u)
// 启动gPRC服务端
if err := s.Serve(listen); err != nil {
log.Fatal(err)
}
}
client.go
package main
import (
pb "awesomeProject2/pb"
"context"
"google.golang.org/grpc"
"log"
"fmt"
)
func main() {
// 创建与gRPC服务端的连接
conn, err := grpc.Dial("127.0.0.1:8090", grpc.WithInsecure())
if err != nil {
log.Fatal(err)
}
defer conn.Close()
// 实例化gRPC客户端
client := pb.NewUserInfoServiceClient(conn)
// 组装参数
req := new(pb.UserRequest)
req.Name = "王哈哈"
resp, err := client.GetUserInfo(context.Background(), req)
if err != nil {
log.Fatal(err)
}
fmt.Printf("响应结果: %v\n", resp)
}