主要参考资料:
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支持
git clone https://github.com/google/protobuf.git
cd protobuf/
git clone https://github.com/google/googlemock.git
mv googlemock gmock
./autogen.sh
./configure
make
make check
make install
export LD_LIBRARY_PATH=/usr/local/lib:/usr/lib:/usr/local/lib64:/usr/lib64
代码编译
- proto文件
- 文件
proto/hello.proto
- 内容
syntax = "proto3";
service Hello {
rpc Ping(Request) returns (Response) {}
}
message Request {
string name = 1;
}
message Response {
string msg = 1;
}
- 编译
protoc --go_out=. --micro_out=. ./proto/hello.proto
- 结果
hello.micro.go
hello.pb.go
- service
- 文件
services/hello.go
- 内容
package main
import (
"context"
"fmt"
proto "../proto" // 路径需指向上述 proto 文件所在目录
micro "github.com/micro/go-micro"
)
type Hello struct{}
func (h *Hello) Ping(ctx context.Context, req *proto.Request, res *proto.Response) error {
res.Msg = "Hello " + req.Name
return nil
}
func main() {
service := micro.NewService(
micro.Name("hellooo"), // 服务名称
)
service.Init()
proto.RegisterHelloHandler(service.Server(), new(Hello))
if err := service.Run(); err != nil {
fmt.Println(err)
}
}
- 运行
go run services/hello.go
- client
- 文件
clients/helloclient.go
- 内容
package main
import (
"context"
"fmt"
proto "../proto"
micro "github.com/micro/go-micro"
)
func main() {
service := micro.NewService(micro.Name("hello.client")) // 客户端服务名称
service.Init()
helloservice := proto.NewHelloService("hellooo", service.Client())
res, err := helloservice.Ping(context.TODO(), &proto.Request{Name: "World ^_^"})
if err != nil {
fmt.Println(err)
}
fmt.Println(res.Msg)
}
- 运行
go run clients/helloclient.go
FAQ:
Q:protoc-gen-go: program not found or is not executable
A:
需要加入环境变量
在~/.bashrc 中加入,并使生效
export PATH = "PATH:$GOPATH/bin"