补充 service

This commit is contained in:
yumaojun03 2025-08-24 14:14:55 +08:00
parent 078be130d7
commit 47b735fea1
3 changed files with 64 additions and 3 deletions

View File

@ -105,7 +105,6 @@ service HelloService {
protoc -I=. --go-grpc_out=. --go-grpc_opt=module="122.51.31.227/go-course/go18" skills/rpc/protobuf/hello_service/interface.proto
```
interface_grpc.pb.go
```go
// 服务端接口

View File

@ -1,3 +1,40 @@
package main
func main() {}
import (
"context"
"log"
"net"
"122.51.31.227/go-course/go18/skills/rpc/protobuf/hello_service"
"google.golang.org/grpc"
)
func main() {
// 首先是通过grpc.NewServer()构造一个gRPC服务对象
grpcServer := grpc.NewServer()
// SDK 提供 服务实现对象的注册
hello_service.RegisterHelloServiceServer(grpcServer, &HelloService{})
lis, err := net.Listen("tcp", ":1234")
if err != nil {
log.Fatal(err)
}
// 然后通过grpcServer.Serve(lis)在一个监听端口上提供gRPC服务
grpcServer.Serve(lis)
}
var _ hello_service.HelloServiceServer = (*HelloService)(nil)
// 实现一个GRPC的对象, 并行实现了 HelloServiceServer 接口
// 该对象就可以注册给GRPC框架
type HelloService struct {
hello_service.UnimplementedHelloServiceServer
}
func (h *HelloService) Hello(ctx context.Context, req *hello_service.Request) (*hello_service.Response, error) {
return &hello_service.Response{
Value: "Hello " + req.Value,
}, nil
}

View File

@ -1,5 +1,30 @@
package main
func main() {
import (
"context"
"fmt"
"log"
"122.51.31.227/go-course/go18/skills/rpc/protobuf/hello_service"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
func main() {
// grpc.Dial负责和gRPC服务建立链接
conn, err := grpc.NewClient("localhost:1234", grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatal(err)
}
defer conn.Close()
// 使用SDK调用远程函数
helloServiceClient := hello_service.NewHelloServiceClient(conn)
resp, err := helloServiceClient.Hello(context.Background(), &hello_service.Request{
Value: "bob",
})
if err != nil {
panic(err)
}
fmt.Println(resp.Value)
}