架構圖
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
)
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)
}
}
# 註冊中心用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去掉即可