Install GRPC reference https://www.cnblogs.com/leisurelylicht/p/Go-an-zhuanggRPC.html
Install the protobuf reference https://blog.csdn.net/u013457167/article/details/83864436
1. Hello. Proto file
syntax = "proto3"; // Specify the proto version
package hello; // Specify the default package name
// Define the Hello service
service Hello {
// Define SayHello
rpc SayHello(HelloRequest) returns (HelloResponse) {}
}
// HelloRequest structure
message HelloRequest {
string name = 1;
}
// HelloResponse Response structure
message HelloResponse {
string message = 1;
}Copy the code
Run the command in the current file to generate the hello.pd.go file:
protoc --go_out=plugins=grpc:./ ./hello.protosCopy the code
Part of the hello.pd.go file
// HelloServer is the server API for Hello service.
type HelloServer interface {
// Define SayHello
SayHello(context.Context, *HelloRequest) (*HelloResponse, error)
}
// HelloClient is the client API for Hello service.
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type HelloClient interface {
// Define SayHelloSayHello(ctx context.Context, in *HelloRequest, opts ... grpc.CallOption) (*HelloResponse, error) }Copy the code
2. Write server-side code
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/grpclog"
pd "hello/myproto"
"net"
)
const(
Address = "127.0.0.1:9999"
)
// Define the structure
type helloService struct{}
// Implements the SayHello method in the HelloServer interface
func (h *helloService)SayHello(ctx context.Context, in *pd.HelloRequest)(*pd.HelloResponse, error) {
fmt.Println(in.Name, "Request service")
res := new(pd.HelloResponse)
res.Message = "hello" + "" + in.Name
return res, nil
}
func main(a) {
var (
HelloService = helloService{}
listen net.Listener
err error
)
// Establish a TCP connection
if listen, err = net.Listen("tcp", Address); err ! =nil{
grpclog.Fatalln(err)
}
// Instantiate GRPC Server
s := grpc.NewServer()
/ / HelloService registration
pd.RegisterHelloServer(s, &HelloService)
// Enable service listening
s.Serve(listen)
}
Copy the code
3. Write client code
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/grpclog"
pd "hello/myproto"
)
const (
Address = "127.0.0.1:9999"
)
func main(a) {
var(
conn *grpc.ClientConn
err error
res *pd.HelloResponse
)
// Establish a connection
// grpc.withinsecure () Ignores certificate authentication
ifconn, err = grpc.Dial(Address, grpc.WithInsecure()); err ! =nil{
grpclog.Fatalln(err)
}
// Initialize the client
c := pd.NewHelloClient(conn)
// Instantiate HelloRequest
req := pd.HelloRequest{Name:"zhe"}
// Call the SayHello method of the HelloClient interface
ifres, err = c.SayHello(context.Background(), &req); err ! =nil{
grpclog.Error(err)
}
fmt.Print(res.Message)
}
Copy the code