主要参考资料:
https://segmentfault.com/a/1190000017572032
consul
- 安装
参考:https://www.cnblogs.com/speeddog/p/7183943.html
启动命令改为
consul agent -data-dir=/usr/local/consuldatal -server -bootstrap -bind 127.0.0.1 -dev
尝试设置为外网地址,被提示有错误,只好用回本地IP:
Error starting agent: Failed to start Consul server: Failed to start RPC layer: listen tcp 外网IP:8300: bind: cannot assign requested address
、
安装go-micro框架
- go get github.com/micro/micro
隐含需要:
git支持
yum -y install git
protoc支持
1git clone https://github.com/google/protobuf.git 2cd protobuf/ 3git clone https://github.com/google/googlemock.git 4mv googlemock gmock 5./autogen.sh 6./configure 7make 8make check 9make install 10 11export LD_LIBRARY_PATH=/usr/local/lib:/usr/lib:/usr/local/lib64:/usr/lib64
代码编译
- proto文件
- 文件
proto/hello.proto
- 内容
1syntax = "proto3"; 2service Hello { 3 rpc Ping(Request) returns (Response) {} 4} 5 6message Request { 7 string name = 1; 8} 9 10message Response { 11 string msg = 1; 12}
- 编译
protoc --go_out=. --micro_out=. ./proto/hello.proto
- 结果
hello.micro.go
hello.pb.go
- service
- 文件
services/hello.go
- 内容
1package main 2 3import ( 4 "context" 5 "fmt" 6 7 proto "../proto" // 路径需指向上述 proto 文件所在目录 8 micro "github.com/micro/go-micro" 9) 10 11 12type Hello struct{} 13 func (h *Hello) Ping(ctx context.Context, req *proto.Request, res *proto.Response) error { 14 res.Msg = "Hello " + req.Name 15 return nil 16} 17 18func main() { 19 service := micro.NewService( 20 micro.Name("hellooo"), // 服务名称 21 ) 22 service.Init() 23 proto.RegisterHelloHandler(service.Server(), new(Hello)) 24 if err := service.Run(); err != nil { 25 fmt.Println(err) 26 } 27}
- 运行
go run services/hello.go
- client
- 文件
clients/helloclient.go
- 内容
1package main 2 3import ( 4 "context" 5 "fmt" 6 7 proto "../proto" 8 micro "github.com/micro/go-micro" 9) 10 11func main() { 12 service := micro.NewService(micro.Name("hello.client")) // 客户端服务名称 13 service.Init() 14 helloservice := proto.NewHelloService("hellooo", service.Client()) 15 16 res, err := helloservice.Ping(context.TODO(), &proto.Request{Name: "World ^_^"}) 17 if err != nil { 18 fmt.Println(err) 19 } 20 fmt.Println(res.Msg) 21}
- 运行
go run clients/helloclient.go
FAQ:
Q:protoc-gen-go: program not found or is not executable
A:
需要加入环境变量
在~/.bashrc 中加入,并使生效
export PATH = "PATH:$GOPATH/bin"