Docker installation Consul

Docker run -d --name=consul -p 85:8500 Consul agent-server-bootstrap-uI-client 0.0.0.0 docker run -d --name=consul -p 85:8500 Consul agent-server-bootstrap-client 0.0.0.0Copy the code
After the operation,http://127.0.0.1:8500Accessing the UI

willserviceRegistered with the Consul
// @author Walker
// @time 2020/11/13 15:28
package main

import (
	"github.com/gin-gonic/gin"
	"github.com/micro/go-plugins/registry/consul"
	"github.com/micro/go-micro/registry"
	"github.com/micro/go-micro/web"
	"net/http"
)

func main(a) {
	// Connect to Consul
	c := consul.NewRegistry(
		registry.Addrs("127.0.0.1:8500"),
	)

	r := gin.Default()
	r.GET("/".func(c *gin.Context) {
		c.String(http.StatusOK, "gin server...")
	})

	s := web.NewService(
		// Define the service name
		web.Name("goodService"),

		// Register with Consul
		web.Registry(c),

		web.Address(": 8001"),
		web.Metadata(map[string]string{"protocol": "http"}),
		web.Handler(r),
)

	s.Run()
}
Copy the code
After the service is run, you can view the newly registered service on Consul’s UI

And then to achieveservicefound
// @author Walker
// @time 2020/11/13 15:56
package main

import (
	"fmt"
	"github.com/micro/go-micro/client/selector"
	"github.com/micro/go-micro/registry"
	"github.com/micro/go-plugins/registry/consul"
	"log"
	"time"
)

func main(a) {
	/ / connect the Consul
	c := consul.NewRegistry(registry.Addrs("127.0.0.1:8500"))

	// Based on the service name defined earlier
	// We defined the server name as "goodService"
	s, err := c.GetService("goodService")

	iferr ! =nil {
		log.Fatal("server gain fail..")}// Get one of these random instances
	// There is currently only one instance, but the next article will focus on building multiple services
	// Go-Micro's load balancing algorithm provides two types
	// RoundRobin
	// Random(Random algorithm)
	// Random() is used here to demonstrate
	n := selector.Random(s)

	// Return a func()
	sv, e := n()

	ife ! =nil {
		log.Fatal("selector fail..")
	}

	fmt.Println("Id:", sv.Id)
	fmt.Println("Address:", sv.Address)
	fmt.Println("Metadata:", sv.Metadata)
	// Sleep for 1s to observe the results
	time.Sleep(time.Second * 1)}Copy the code
Post run output
# Consistent with what is displayed on the Consul interface
Id: 45ffe64f-952c-449f-88a6-c2db1dc2be66
Get the LAN IP, everyone test environment will be differentAddress: 192.168.88.109:8001 Metadata: map [protocol: HTTP]Copy the code