How do GO-Micro V3 configure consul Registry and Operation Profile Center

The source address

  • The source address
  • Comprehensive micro service project of Airentals

preface

The Go-Micro framework provides a standard interface, Registry, for service registration discovery. You can customize your own service registration and discovery simply by implementing this interface. However, there is an official interface implementation for major registries, and most of the time we don’t need to write it from scratch.

Code warehouse

The sample code

Docker installation Consul

Consul is used here for demonstration because Consul comes with its own UI for easy operation

Docker pull consul # Default pull latestCopy the code

Run standalone Consul

docker run -d -p 8500:8500 --restart=always --name=consul consul:latest agent -server -bootstrap -ui -node=1 - client = '0.0.0.0'Copy the code

The parameters are described as follows:

  • Agent: Starts the Agent process.

  • Server: Enables Consul Server mode

  • Client: Enables Consul Client mode.

  • Bootstrap: indicates that the node is the Server Leader and each data center can run only one Server. Technically, the Leader is elected using the Raft algorithm, but a boot Leader is required when the cluster is first booted, and it is recommended not to use this flag after the cluster is booted.

  • UI: Indicates that the Web UI manager is started. Port 8500 is opened by default, so the Docker command is used to open port 8500.

  • Node: node name. It must be unique in the cluster. The default name is the host name of the node.

  • Client: Consul Service Listening address. This address provides HTTP, DNS, and RPC services. The default value is 127.0.0.1, so it does not provide external services

  • Join: Indicates to join a cluster. Such as: – json = 192.168.0.11.

After successful operation, visit http://localhost:8500 to access consul’s built-in UI, as shown in the following figure:

The key code

package main

import (
	"github.com/asim/go-micro/plugins/registry/consul/v3"
	"github.com/asim/go-micro/v3"
	"github.com/asim/go-micro/v3/logger"
	"github.com/asim/go-micro/v3/registry"
	"go-micro-examples/registerConfiguration/handler"
	pb "go-micro-examples/registerConfiguration/proto"
)

func main(a) {
	// Register consul
	reg := consul.NewRegistry(func(options *registry.Options) {
		options.Addrs =[]string{"127.0.0.1:8500"}})// Create service
	srv := micro.NewService(
		micro.Name("go.micro.srv.registerconfiguration"),
		micro.Version("latest"),
		// Register with Consul Centre
		micro.Registry(reg),
	)

	// Register handler
	if err := pb.RegisterRegisterConfigurationHandler(srv.Server(), new(handler.RegisterConfiguration)); err ! =nil {
		logger.Fatal(err)
	}

	// Run service
	iferr := srv.Run(); err ! =nil {
		logger.Fatal(err)
	}
}
Copy the code

Go-micro V3 provides plugins and you just need to import and create an instance and register with micro-.registry

After operation, the effect picture is as follows:

Configuration center

Click Key/Value to create directory micro/config, and then create mysql, Redis, Logger and Server directories respectively in config directory, as shown below:

Mysql > select * from ‘mysql’;

{" host ", "192.168.0.65", / / host address "user" : "root", / / the user name "PWD" : "123456", "database" : / / password "Go-shop-b2b2c ", // database "port": 3306 // port}Copy the code

Then registerConfiguration creates the config directory and config.go and mysql.go files

config.go

package config

import (
	"github.com/asim/go-micro/plugins/config/source/consul/v3"
	"github.com/asim/go-micro/v3/config"
	"strconv"
)

const (
	Host = "192.168.0.65"
	Port = 8500
	Prefix = "/micro/config"
)

// GetConsulConfig Set configuration center
func GetConsulConfig(a) (config.Config, error) {
	// Add configuration center
	} // The configuration center uses Consul key/value mode
	consulSource := consul.NewSource(
		// Set the configuration center address
		consul.WithAddress(Host+":"+strconv.FormatInt(Port, 10)),
		// Set the prefix. The default is /micro/config
		consul.WithPrefix(Prefix),
		// Whether to remove the prefix. If this parameter is set to true, the configuration can be obtained without the prefix
		consul.StripPrefix(true),// Initialize the configuration
	conf, err := config.NewConfig()
	iferr ! =nil {
		return conf, err
	}
	// Load the configuration
	err = conf.Load(consulSource)
	return conf, err
}
Copy the code

mysql.go

package config

import "github.com/asim/go-micro/v3/config"

// MysqlConfig creates a structure
type MysqlConfig struct {
	Host     string `json:"host"`
	User     string `json:"user"`
	Pwd      string `json:"pwd"`
	Database string `json:"database"`
	Port     int64  `json:"port"`
}

GetMysqlFromConsul Gets the mysql configuration
func GetMysqlFromConsul(config config.Config, path ...string) (*MysqlConfig, error) {
	mysqlConfig := &MysqlConfig{}
	// Get the configurationerr := config.Get(path...) .Scan(mysqlConfig)iferr ! =nil {
		return nil, err
	}
	return mysqlConfig, nil
}
Copy the code

main.go

The configuration information of the configuration center can be obtained before starting the service with the following code:

// Configure the center
consulConfig, err := config.GetConsulConfig("127.0.0.1".8500."/micro/config")
iferr ! =nil {
    logger.Fatal(err)
}

// Mysql configuration information
mysqlInfo, err := config.GetMysqlFromConsul(consulConfig, "mysql")
iferr ! =nil {
    logger.Fatal(err)
}

logger.Info(Mysql > select * from 'Mysql';, mysqlInfo)
Copy the code

After the operation, the following figure is displayed. It can be seen that the configuration information just entered has been successfully obtained: