实测go-micro入门demo

实测go-micro入门demo

1、启动consul

使用一下命令启动consul agent。

consul agent -dev -client 0.0.0.0

注意,一定要加-client 0.0.0.0,否则其他机器是无法访问consul的。

2、创建一个服务(math_service)

main.go

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/micro/go-micro/v2/registry"
	"github.com/micro/go-micro/v2/web"
	"github.com/micro/go-plugins/registry/consul/v2"
	"strconv"
)

var reg registry.Registry

func init()  {
	reg = consul.NewRegistry(registry.Addrs("127.0.0.1:8500"))
}

func InitWeb() *gin.Engine {
	r := gin.Default()
	r.GET("/math/add", func(c *gin.Context) {
		x, _ := strconv.Atoi(c.Query("x"))
		y, _ := strconv.Atoi(c.Query("y"))

		z := x + y
		c.String(200, fmt.Sprintf("z=%d", z))
	})

	return r
}

func main() {
	service := web.NewService(
		web.Name("math_service"),
		web.Address("127.0.0.1:50000"),  //注意 不要写成 ":50000",要写完整的ip "127.0.0.1:50000"
		web.Handler(InitWeb()),
		web.Registry(reg),
		)

	_ = service.Run()
}

跑起服务如下:

注册中心

测试服务

调用显示:

3、另一个服务(other_service), 通过http查找到consul里的注册服务调用math_service

main.go

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/micro/go-micro/v2/client/selector"
	"github.com/micro/go-micro/v2/registry"
	"github.com/micro/go-micro/v2/web"
	"github.com/micro/go-plugins/registry/consul/v2"
	"io/ioutil"
	"net/http"
)

var reg registry.Registry

func init()  {
	reg = consul.NewRegistry(registry.Addrs("127.0.0.1:8500"))
}

func InitWeb() *gin.Engine  {
	r := gin.Default()
	r.GET("/other/test", func(c *gin.Context) {
		content := Call(c.Query("x"), c.Query("y"))
		c.String(200, content)
	})

	return r
}

func Call(x, y string) string  {
	address := GetServiceAddress("math_service")
	url := fmt.Sprintf("http://"+address+"/math/add?x=%s&y=%s", x, y)

	response, err := http.Get(url)
	if err != nil{
		return err.Error()
	}

	content, _ := ioutil.ReadAll(response.Body)
	response.Body.Close()


	return string(content)
}

func GetServiceAddress(name string) (address string)  {
	list,_ := reg.GetService(name)

	var services []*registry.Service

	for _,value := range list{
		services = append(services, value)
	}

	next := selector.RoundRobin(services)
	if node, err := next(); err == nil {
		address = node.Address
	}

	return
}

func main() {
	service := web.NewService(
		web.Name("other_service"),
		web.Address("127.0.0.1:50001"),
		web.Handler(InitWeb()),
		web.Registry(reg),
		)

	_ = service.Run()
}

启动服务

调用服务

math_service控制台显示

other_service控制台显示

 

hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » 实测go-micro入门demo