创建项目
go mod init gomicro-demo
编写proto文件
syntax = "proto3";
option go_package = "./;hellomicro";
service HelloMicroService{
rpc SayHelloMicro(HelloRequest) returns(HelloResponse){}
}
message HelloRequest{
string Name = 1;
}
message HelloResponse{
string Msg = 1;
}
编译proto文件
protoc --micro_out=./proto/hellomicro --go_out=./proto/hellomicro ./proto/hellomicro.proto
注意
protoc生成的hellomicro.pb.micro.go还是使用的v1版本,这里改成v2版本
编写服务端
默认使用mdns做注册中心,这里使用consul做注册中心
package main
import (
"context"
"fmt"
"github.com/micro/go-micro/v2"
"github.com/micro/go-micro/v2/registry"
"github.com/micro/go-plugins/registry/consul/v2"
"gomicro-demo/proto/hellomicro"
)
type HelloMicroService struct {
}
func(hm *HelloMicroService) SayHelloMicro(ctx context.Context, in *hellomicro.HelloRequest, out *hellomicro.HelloResponse) error{
out.Msg = "Hello,Micro:" + in.Name
return nil
}
func main() {
// 配置consul做配置中心
reg := consul.NewRegistry(func(op *registry.Options) {
op.Addrs = []string{
"127.0.0.1:8500",
}
})
// 创建服务
service := micro.NewService(
micro.Name("hello"),
micro.Registry(reg),
)
// 初始化服务
service.Init()
// 注册服务
hellomicro.RegisterHelloMicroServiceHandler(service.Server(),new(HelloMicroService))
// 启动服务
e := service.Run()
if e != nil {
fmt.Println("服务启动失败")
}
}
编写客户端
package main
import (
"context"
"fmt"
"github.com/micro/go-micro/v2"
"github.com/micro/go-micro/v2/registry"
"github.com/micro/go-plugins/registry/consul/v2"
"gomicro-demo/proto/hellomicro"
)
func main() {
reg := consul.NewRegistry(func(op *registry.Options) {
op.Addrs = []string{
"127.0.0.1:8500",
}
})
// 创建服务
service := micro.NewService(
micro.Name("hello.client"),
micro.Registry(reg),
)
// 初始化服务
service.Init()
// 创建客户端连接
microService := hellomicro.NewHelloMicroService("hello", service.Client())
// 调用服务
response, e := microService.SayHelloMicro(context.Background(), &hellomicro.HelloRequest{Name: "lisi"})
if e != nil {
fmt.Println("响应错误:",e)
return
}
fmt.Println("响应结果:",response.Msg)
}
启动服务端
启动客户端
启动consul
consul agent -dev