架构图
- 下载依赖
go get github.com/micro/micro/v2@v2.5
go get github.com/micro/go-micro/v2@v2.5
go.mod文件
module jtthink
go 1.14
require (
github.com/golang/protobuf v1.4.2
github.com/micro/go-micro/v2 v2.5.0
github.com/micro/micro/v2 v2.5.0 // indirect
)
- 代码
User.proto
syntax = "proto3";
package Users;
service UserService {
rpc Test(UserRequest) returns (UserResponse) { }
}
message UserRequest {
string id = 1;
}
message UserResponse {
string ret = 2;
}
编译
protoc --proto_path=src/protos --micro_out=src/Users --go_out=src/Users Users.proto
实现代码
package main
import (
"context"
"github.com/micro/go-micro/v2"
"jtthink/src/Users"
"log"
)
type UserService struct{ }
// 测试方法
func (g *UserService) Test(ctx context.Context, req *Users.UserRequest, rsp *Users.UserResponse) error {
rsp.Ret="users"+req.Id
return nil
}
func NewUserService() *UserService {
return &UserService{ }
}
func main() {
//api.jtthink.com --- prefix
service:=micro.NewService(
micro.Name("go.micro.api.jtthink.user"))
service.Init()
err:=Users.RegisterUserServiceHandler(service.Server(),NewUserService())
if err!=nil{
log.Fatal(err)
}
if err = service.Run(); err != nil {
log.Println(err)
}
}
- 执行
api:user.bat文件
# 注册中心用etcd
set MICRO_REGISTRY=etcd
# etcd地址
set MICRO_REGISTRY_ADDRESS=192.168.56.30:23791
go run src/cmd/user_server.go --server_address :9090
gateway:gw.bat文件
# 注册中心用etcd
set MICRO_REGISTRY=etcd
# etcd地址
set MICRO_REGISTRY_ADDRESS=192.168.56.30:23791
set MICRO_CLIENT=grpc
set MICRO_SERVER=grpc
micro api
控制台:web.bat文件
# 注册中心用etcd
set MICRO_REGISTRY=etcd
# etcd地址
set MICRO_REGISTRY_ADDRESS=192.168.56.30:23791
micro web
分别把这三个文件执行,我当前在win上开发,linux把命令里的set去掉即可
- 测试