go-micro+consul+gin
安装(前提是本地已安装protobuf和protof的go扩展)
go get github.com/micro/micro
go get github.com/micro/go-micro
go get github.com/micro/protoc-gen-micro
go get github.com/micro/go-plugins/registry/consul
支持consul需要单独安装这个包
go get github.com/micro/go-plugins/registry/consul
micro生成新项目
micro new --gopath=false --type=srv micpro
进入到 proto文件的同级目录,然后执行以下命令生成go文件
protoc --micro_out=. --go_out=. *.proto
package main
import (
"github.com/micro/go-micro"
"github.com/micro/go-micro/util/log"
"github.com/micro/go-plugins/registry/consul"
"micpro/handler"
micpro "micpro/proto/micpro"
)
func main() {
consulRegis := consul.NewRegistry()
// New Service
service := micro.NewService(
micro.Name("go.micro.srv.micpro"),
micro.Version("latest"),
micro.Registry(consulRegis),
micro.Address("127.0.0.1:10345"),
)
// Initialise service
service.Init()
// Register Handler
micpro.RegisterMicproHandler(service.Server(), new(handler.Micpro))
// Run service
if err := service.Run(); err != nil {
log.Fatal(err)
}
}
将micro框架proto目录下的文件拷贝到gin目录下,然后在main.go中使用consul
package main
import (
context2 "context"
"fmt"
micpro "gintemp/proto/micpro"
"github.com/gin-gonic/gin"
"github.com/micro/go-micro"
"github.com/micro/go-micro/client"
"github.com/micro/go-plugins/registry/consul"
"time"
)
func microCall(context *gin.Context){
reg := consul.NewRegistry()
service := micro.NewService(micro.Registry(reg))
micServ := micpro.NewMicproService("go.micro.srv.micpro",service.Client())
res,err := micServ.Call(context2.TODO(),&micpro.Request{Name:"mayuan"},func(o *client.CallOptions) {
o.RequestTimeout = time.Second * 30
o.DialTimeout = time.Second * 30
})
if err != nil{
fmt.Println(err)
}
context.Writer.WriteString(res.Msg)
}
func main() {
route := gin.Default()
route.GET("/", microCall)
route.Run(":8080")
}