文档
m1.topgoer.com/ 1.x
m2.topgoer.com/ 2.x
github 文档 github.com/real-jacket…
相关项目
安装相应的包
go get github.com/micro/micro
go get github.com/micro/go-micro
go get github.com/micro/protoc-gen-micro
hello.proto
syntax = "proto3";
option go_package = "pb;proto";
// 定义需要的结构体参数
message InfoRequest {
string name = 1;
}
message InfoResponse {
string msg = 1;
}
service Hello {
rpc Info(InfoRequest) returns (InfoResponse) {}
}
server.go
package main
import (
"context"
"fmt"
"github.com/micro/go-micro"
"log"
pb "go-micro-demo/pb"
)
type Hello struct{}
// 实现接口方法
func (g *Hello) Info(ctx context.Context, req *pb.InfoRequest, resp *pb.InfoResponse) error {
resp.Msg = fmt.Sprintf("hello %v\n", req.Name)
return nil
}
func main() {
// 1.得到微服务实例
service := micro.NewService(
// 设置微服务的名字, 用来做访问用的
micro.Name("hello"),
)
// 2.初始化
service.Init()
// 3.服务注册
err := pb.RegisterHelloHandler(service.Server(), new(Hello))
if err != nil {
log.Fatal(err)
}
// 4.启动微服务
if err := service.Run(); err != nil {
log.Fatal(err)
}
}
生成 xx.pb.go 和 xx.pb.micro.go 文件
protoc -I . --micro_out=. --go_out=. hello.proto
命令行调用
micro call hello Hello.Info {\"name\":\"王哈哈\"}
返回
{
"msg": "hello 王哈哈\n"
}
api.proto
syntax = "proto3";
option go_package = "pb;proto";
message CallRequest {
string name = 1;
}
message CallResponse {
string message = 1;
}
// 空的请求参数
message EmptyRequest {}
// 空的响应
message EmptyResponse {}
service Example {
rpc Call (CallRequest) returns (CallResponse) {}
}
service Foo {
rpc Bar (EmptyRequest) returns (EmptyResponse) {}
}
生成 xx.micro.pb.go 和 xx.pb.go 文件
protoc -I . --micro_out=. --go_out=. api.proto
server.go
package main
import (
"context"
"fmt"
"github.com/micro/go-micro"
pb "go-micro-demo/pb"
"log"
)
type Example struct{}
func (e *Example) Call (ctx context.Context, req *pb.CallRequest, resp *pb.CallResponse) error {
resp.Message = fmt.Sprintf("hello %v\n", req.Name)
return nil
}
type Foo struct {}
func (f *Foo) Bar (ctx context.Context, req *pb.EmptyRequest, resp *pb.EmptyResponse) error {
log.Println("收到Foo.Bar请求...")
return nil
}
func main() {
// 1.得到微服务实例
service := micro.NewService(
micro.Name("go.micro.api.example"),
)
// 初始化
service.Init()
// 注册Example的接口
if err := pb.RegisterExampleHandler(service.Server(), new(Example)); err != nil {
log.Fatal(err)
}
// 注册Foo的接口
if err := pb.RegisterFooHandler(service.Server(), new(Foo)); err != nil {
log.Fatal(err)
}
// 启动
if err := service.Run(); err != nil {
log.Fatal(err)
}
}
运行
go run main.go
使用 micro 运行http端口
micro api --handler=rpc
使用 postman 访问