0.目录
- go-micro 安装
- go-micro+consul服务注册、服务发现
网上大多数go-micro的都是v2 v3 本文使用最新的 v4版本
1. 启动consul
下载:https://www.consul.io/downloads
consul agent -h 查看帮助
Windows启动
consul agent -server -bootstrap-expect 1 -data-dir C:\Temp\consul\data -node=n1 -bind=x.x.x.x -ui -rejoin -config-dir=C:\Temp\consul\config -client 0.0.0.0
Linux启动
consul agent -server -bootstrap-expect 1 -data-dir /tmp/consul -node=n1 -bind=x.x.x.x -ui -rejoin -config-dir=/etc/consul.d/ -client 0.0.0.0
其中x.x.x.x换为外网可访问的网卡地址,本地测试可以用127.0.0.1
2. 微服务程序
在上一篇文章最后创建的微服务xxxxxxx,main.go中,添加关于consul的代码 import "github.com/asim/go-micro/plugins/registry/consul/v4"
consulReg:= consul.NewRegistry(func(options *registry.Options) {
options.Addrs =[]string{"x.x.x.x:8500"}
})
srv := micro.NewService(
micro.Name(service),
micro.Version(version),
micro.Registry(consulReg),
)
登录网址:x.x.x.x:8500 就能看到 XXXXXXX已经注册到consul上了 图上有2个instances 是因为我go run了2次 启了2个服务,都注册上了,非常简单
3. Gin客户端通过服务发现找到微服务
package main
import (
"context"
xxxxxxx "gin_client/proto"
"log"
"net/http"
"go-micro.dev/v4"
"go-micro.dev/v4/registry"
"github.com/asim/go-micro/plugins/registry/consul/v4"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.GET("/", func(c *gin.Context) {
consulReg := consul.NewRegistry(func(options *registry.Options) {
options.Addrs = []string{"192.168.31.74:8500"}
})
service := micro.NewService(
micro.Registry(consulReg),
)
mc := xxxxxxx.NewXxxxxxxService("xxxxxxx", service.Client())
resp, err := mc.Call(context.TODO(), &xxxxxxx.CallRequest{Name: "xuehu96"})
if err != nil {
log.Println(err.Error())
c.String(http.StatusBadRequest, "hello")
return
}
c.String(http.StatusOK, resp.Msg)
})
router.Run(":8848")
}
使用ApiPost6测试(支持国产)
|