栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

Go微服务——go-micro v4服务注册 Gin使用consul服务发现

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Go微服务——go-micro v4服务注册 Gin使用consul服务发现

0.目录
  1. go-micro 安装
  2. 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:Tempconsuldata -node=n1 -bind=x.x.x.x -ui -rejoin -config-dir=C:Tempconsulconfig -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"

	// Register consul
    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), // 注册Consul
	)


登录网址: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) {
		// consul
		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测试(支持国产)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/903276.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号