最近开始完整的学go , 这里简单记录下用go 开发的grpc demo。这里主要实现的是client 传id参数,rpc调用getUser 方法获取server 结果。
1. 开发配置
2. 开发代码
- 新建项目目录,一般是在gopath下面
- user.proto 文件内容如下
syntax = "proto3";
package user;
//新版本需要的配置
option go_package = "./user";
message UserRequest {
int32 id = 1;
}
message UserResponse {
int32 id = 1;
string name = 2;
}
service UserService {
rpc getUser(UserRequest) returns (UserResponse) {};
}
protoc user.proto --go_out=./protobuf --go-grpc_out=./protobuf --go-grpc_opt=require_unimplemented_servers=false
require_unimplemented_servers=false 这个配置不加,会存在兼容问题,有个接口需要实现
package main
import (
"context"
"demo/grpc/protobuf/user"
"fmt"
"google.golang.org/grpc"
"net"
)
type UserServiceInterface interface {
GetUser(ctx context.Context, req *user.UserRequest) (*user.UserResponse, error)
}
type UserServiceStruct struct {
}
func NewUserService() UserServiceInterface {
return &UserServiceStruct{}
}
func (userService *UserServiceStruct) GetUser(ctx context.Context, req *user.UserRequest) (*user.UserResponse ,error) {
response := &user.UserResponse {
Id: req.Id,
Name: "Hello World",
}
return response,nil
}
func main() {
l,err := net.Listen("tcp", "127.0.0.1:8889")
if err != nil {
panic(err)
}
fmt.Println("listen on 127.0.0.1:8889")
grpcServer := grpc.NewServer()
var userService UserServiceInterface
userService = NewUserService()
user.RegisterUserServiceServer(grpcServer, userService)
err = grpcServer.Serve(l)
if err != nil {
println(err)
}
}
package main
import (
"context"
"demo/grpc/protobuf/user"
"encoding/json"
"fmt"
"google.golang.org/grpc"
)
func main(){
conn, err := grpc.Dial("127.0.0.1:8889", grpc.WithInsecure())
if err != nil {
panic(err)
}
defer conn.Close()
client := user.NewUserServiceClient(conn)
req := &user.UserRequest{
Id: 1,
}
response, _ := client.GetUser(context.Background(), req)
resp,err := json.Marshal(response)
fmt.Printf("%s", resp)
}
3. 安装依赖运行
- go mod tidy 安装相关依赖
- go run server.go
运行结果:listen on 127.0.0.1:8889
运行结果:{“id”:1,“name”:“Hello World”}
|