代码地址
go micro 简单使用
- 目录结构 go init go_micro_learn
- proto // 放proto文件
- server.go //微服务服务端
- client.go // 微服务客户端
- 使用proto生成文件, 生成的包名为pb
syntax = "proto3";
option go_package = "./;pb";
service Greeter {
rpc Hello(HelloRequest) returns (HelloResponse) {}
}
message HelloRequest {
string name = 1;
}
message HelloResponse {
string greeting = 2;
}
使用protoc 生成.go 文件 protoc --proto_path=. --go_out=. --micro_out=. proto/greeter.proto
- server端
package main
import (
"fmt"
pb "go_micro_learn/proto"
"context"
micro "github.com/micro/go-micro/v2"
)
type Greeter struct {
}
func (g *Greeter) Hello(ctx context.Context, req *pb.HelloRequest, res *pb.HelloResponse) error {
fmt.Println("server")
res.Greeting = "接收到的值为" + req.Name
return nil
}
func main() {
// 创建服务
service := micro.NewService(
micro.Name("greeter.server"), // 服务名为greeter.server
micro.Address("0.0.0.0:9630"),
)
// 初始化服务
service.Init()
//注册服务 参数1为micro服务
pb.RegisterGreeterHandler(service.Server(), new(Greeter))
service.Run()
}
- client端
package main
import (
"context"
"fmt"
pb "go_micro_learn/proto"
micro "github.com/micro/go-micro/v2"
)
func main() {
service := micro.NewService(micro.Name("geeter.client"))
service.Init()
// 创建新客户端
greeter := pb.NewGreeterService("greeter.server", service.Client()) // 定义要访问的服务
// 调用服务的Hello方法
res, err := greeter.Hello(context.Background(), &pb.HelloRequest{
Name: "abc",
})
fmt.Println("res", res)
fmt.Println(err)
}
遇到的报错
使用grpc报错 etcd client3
报错信息 grpc 版本问题
github.com/coreos/etcd/clientv3/balancer/resolver/endpoint
../../pkg/mod/github.com/coreos/etcd@v3.3.18+incompatible/clientv3/balancer/resolver/endpoint/endpoint.go:114:78: undefined: resolver.BuildOption
../../pkg/mod/github.com/coreos/etcd@v3.3.18+incompatible/clientv3/balancer/resolver/endpoint/endpoint.go:182:31: undefined: resolver.ResolveNowOption
# github.com/coreos/etcd/clientv3/balancer/picker
../../pkg/mod/github.com/coreos/etcd@v3.3.18+incompatible/clientv3/balancer/picker/err.go:37:44: undefined: balancer.PickOptions
../../pkg/mod/github.com/coreos/etcd@v3.3.18+incompatible/clientv3/balancer/picker/roundrobin_balanced.go:55:54: undefined: balancer.PickOptions
解决方案
go mod 中添加
replace google.golang.org/grpc => google.golang.org/grpc v1.26.0