开发环境配置见之前文章
1.编写proto文件: hello.proto
syntax = "proto3";
option go_package=".;service";
service SayHello{
rpc SayHello(HelloRequest) returns (HelloResponse) {}
}
message HelloRequest{
string requestName=1;
}
message HelloResponse {
string responseMsg=1;
}
2.执行命令:
protoc --go_out=. hello.proto
protoc --go-grpc_out=. hello.proto
生成hello的go和grpc的go代码
3.main写服务
服务端编写:
创建gprc sever对象,理解它是Server端的抽象对象
将server(包含需要被调用的服务端接口)注册到gprc server的内部注册中心,这样在接受到请求时,通过内部的服务,发现该服务端接口并转接将进行逻辑处理
创建Listen,监听TPC端口
gprc server开始lis.Accept,知道Stop
客户端编写:
创建与给定目标(服务端)的连接交互
创建server的客户端对象
发送rpc请求,等待同步响应,得到回调后返回响应结构
输出响应结果
## 服务端main(),实现sayHello方法和server结构体
## 三个要素,gprc服务,监听端口,注册服务
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"net"
pb "xxb-grpc-study/hello-server/proto"
)
type server struct {
pb.UnimplementedSayHelloServer
}
func (s *server) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloResponse, error) {
return &pb.HelloResponse{ResponseMsg: "hello" + req.RequestName}, nil
}
func main() {
//kaiqi duankou
listen, err := net.Listen("tcp", "9090")
if err != nil {
fmt.Printf("listen error", err)
}
//chuangjian rpgc fuwu
grpcServer := grpc.NewServer()
//zai gprc feuwuduan zhuce zji fuwu
pb.RegisterSayHelloServer(grpcServer, &server{})
//qidong fuwu
err_server := grpcServer.Serve(listen)
if err_server != nil {
fmt.Printf("failed to server : %v",err_server)
return
}
}
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"log"
pb "xxb-grpc-study/hello-server/proto"
)
func main() {
//lianjie dao serverduan ,jin yong anquan chuanshu ,wu jiami he yanzheng
conn, err := grpc.Dial("127.0.0.1:9090", grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf("did not connect : %v", err)
}
defer conn.Close()
//jian li lian jie
client := pb.NewSayHelloClient(conn)
//rpc yuan cheng diao yong
resp, _ := client.SayHello(context.Background(), &pb.HelloRequest{RequestName: "kuangshen"})
fmt.Println(resp.GetResponseMsg())
}
注意:本地调试连接grpc,需要关闭clash服务(systemctl stop clash)和禁用网络代理(不需要export_exit)