The author | bin-bin zhang

This article mainly introduces how to use Golang ecosystem’s micro-service framework GO-Micro (V2) to integrate Nacos for service registration and discovery. (Go-Micro is currently version V3, but the project has been renamed nitro for some reasons, which you can check on Github.)

Related background

1. Go-Micro

Go Micro is a basic framework for building microservices based on the Go language. It provides the core components required for distributed development, including RPC and event-driven communication.

Its design philosophy is a “pluggable” plug-in architecture, with its core focus on providing underlying interface definitions and underlying tools that are compatible with various implementations. For example, Go Micro defaults to service discovery via Consul, communication via HTTP, codec via Protobuf and JSON so you can start quickly based on these components provided out of the box, but if needed, You can also replace the default components with other components that match the underlying interface definition, such as service discovery through Nacos, ETcd, or ZooKeeper. This is the advantage of a plug-in architecture: you can replace the top components without changing any of the underlying code.

1) Micro Overview

Micro is a microservices toolkit that includes:

  • API

An API gateway that provides and routes HTTP requests to the corresponding microservice. It acts as a single entry point for microservice access and can also act as a reverse proxy by converting HTTP requests into RPC and forwarding them to the corresponding service.

  • Web

The UI is the Web version of Go-Micro, allowing interactive access to the environment through the UI. In the future, it will also be a way to aggregate miniature Web services. It contains a proxy approach to Web applications. Route /[name] through the registry to the appropriate service. The Web UI will be prefixed with “go.micro-web.” Add (configurable) to the name, look it up in the registry, and then reverse proxy will be done.

  • Sidecar

The HTTP interface version of Go-Micro, which is a way to integrate non-GO applications into a microenvironment.

  • Bot

Hubot-style bots, located in your microservices platform, can interact with Slack, HipChat, XMPP, and more. It provides CLI functionality through messaging. Additional commands can be added to automate common operational tasks.

  • CLI

A direct command line interface to interact with your microservices, which provides a way to observe and interact with the runtime environment.

2) Go-Micro components

A plug-in RPC framework for writing microservices in Go. It provides libraries for service discovery, client load balancing, coding, synchronous and asynchronous communication. Go-micro is a stand-alone library that can be used independently of other toolkits.

Go-micro is a componentized framework, each basic function is an interface, easy to expand. At the same time, the components are layered, with the upper level providing services based on the lower level, constituting the GO-Micro framework as a whole. The components of the GO-Micro framework are:

  • Registry

Provides a service discovery mechanism: resolves service names to service addresses. Currently, supported registries include Consul, ETcd, ZooKeeper, DNS, and Gossip.

  • Selector

Selectors provide load balancing mechanisms through selection. When the client makes a request to the server, it first queries the registry of the service. This typically returns a list of running nodes representing the service. The selector will select one of these nodes for the query. Multiple calls to the selector will allow the balancing algorithm to be used. Current methods are cyclic, random hashing and blacklisting.

  • Broker

Pluggable interfaces for publishing and subscribling.Asynchronous communication between services based on messaging-oriented middleware. HTTP is the default, and messaging-oriented middleware such as Nats, Kafka, RabbitMQ, and HTTP (for development) is commonly used online.

  • Transport

A pluggable interface for transmitting messages from point to point. Current implementations are HTTP, RabbitMQ and Nats. By providing this abstraction, transport can be swapped out seamlessly.

  • Codec

Encoding/decoding of messages between services.

  • Plugins

Micro/Go-Plugins are provided for Go-Micro.

  • Server

The server is the interface to build running microservices. It provides a way to serve RPC requests. The component is based on the above Registry/Selector/Transport/Broker components, provides a service request on a unified entrance.

  • Client

Provides a method for making RPC queries to access microservice clients. It combines registry, selector, proxy and transport. It also provides retry, timeout, usage context, and so on. Similar to a Server component, it is also through the Registry/Selector/Transport/Broker component implementation lookup service, load balance, synchronous communication, asynchronous messaging, and other functions.

2. Nacos

Nacos is a platform for dynamic service discovery, configuration management and service management that makes it easier to build cloud native applications. Nacos is derived from Alibaba’s internal ConfigServer and Diamond, and is their open source implementation. The alibaba soft load team has experienced ten years of experience in this field after experiencing the peak traffic on Singles Day and the super large capacity of Alibaba’s economy, which ensures its stability and functionality.

An overview of Nacos logical architecture and its components:

Quick start

1. The Go-Micro server

1) Install Protoc

Protobuf, short for Protocol Buffers, is a data description language developed by Google and opened source in 2008. When Protobuf was first opened, it was positioned like data description languages such as XML and JSON, with accompanying tools to generate code and serialize structured data. We need to generate server-side code using Protoc.

o get github.com/golang/protobuf/protoc-gen-go
Copy the code

2) Install go-Micro/V2

go install github.com/micro/micro/v2
Copy the code

3) New Golang project (server)

  • Create a proto folder in the project root directory to store protobuf files

  • Create a greeter.proto file in the proto folder

  • The content of the document is as follows:

A handler called Greeter is defined on the server side using a Protobuf file that has a Hello method that receives a HelloRequest and returns a HelloResponse.

syntax = "proto3";
package helloworld;
service Greeter {
    rpc Hello(HelloRequest) returns (HelloResponse) {}
}
message HelloRequest {
    string name = 1;
}
message HelloResponse {
    string greeting = 2;
}
Copy the code
  • Generate the corresponding Go code
protoc  --micro_out=. --go_out=. proto/greeter.proto
Copy the code
  • In proto, two files pb.go and Pb.micro. Go are generated

  • Create server.go and run it
package main
import (
    "context"
    helloworld "go-micro-nacos-demo1/proto"
    "github.com/micro/go-micro/v2"
    "github.com/micro/go-micro/v2/logger"
    "github.com/micro/go-micro/v2/registry"
    nacos "github.com/micro/go-plugins/registry/nacos/v2"
)
type Helloworld struct{}
// Call is a single request handler called via client.Call or the generated client code
func (e *Helloworld) Hello(ctx context.Context, req *helloworld.HelloRequest, rsp *helloworld.HelloResponse) error {
    logger.Info("Received Helloworld.Call request")
    return nil
}
func main() {
    addrs := make([]string, 1)
    addrs[0] = "console.nacos.io:80"
    registry := nacos.NewRegistry(func(options *registry.Options) {
        options.Addrs = addrs
    })
    service := micro.NewService(
        // Set service name
        micro.Name("my.micro.service"),
        // Set service registry
        micro.Registry(registry),
    )
    helloworld.RegisterGreeterHandler(service.Server(), new(Helloworld))
    service.Run()
}
Copy the code
  • On the Nacos Console, you can see that my.micro. Service was successfully registered

2. Go-micro client

  • Create client.go (for demonstration purposes, this article creates cient.go under the same project).

package main import ( "context" "fmt" helloworld "go-micro-nacos-demo1/proto" "github.com/micro/go-micro/v2" "github.com/micro/go-micro/v2/registry" nacos "github.com/micro/go-plugins/registry/nacos/v2" ) const serverName = "my.micro.service" func main() { addrs := make([]string, 1) addrs[0] = "console.nacos.io:80" r := nacos.NewRegistry(func(options *registry.Options) { options.Addrs = addrs }) // Define services, Other optional arguments can be passed to service := micro-newService (micro-name (" my.micro-service.client ") Micro. Registry (r)) / / create a new Client greeter: = helloworld. NewGreeterService (serverName, service Client ()) / / call the greeter RSP, err := greeter.Hello(context.TODO(), &helloworld.HelloRequest{Name: "John"}) if err ! = nil {fmt.println (err)} // Get all services fmt.println (registry.listServices ()) // Get one service, err := registry.GetService(serverName) if err ! = nil {FMT.Println(err)} Err := registry.Watch() fmt.println (services) // Print response request fmt.println (rsp.greeting) go service.run () for {result, err := watch.Next() if len(result.Action) > 0 { fmt.Println(result, err) } } }Copy the code
  • Run the client, and you can see in the NacOS Console that the client service is also registered with NacOS.

  • The call log is printed in the server.go console.

3. The go-Micro integrates Nacos function description

1) server. Go

Server: Use go-Micro to create a server Demo and register with NACOS.

registry := nacos.NewRegistry(func(options *registry.Options) { options.Addrs = addrs }) service := micro.NewService( //  Set service name micro.Name("my.micro.service"), // Set service registry micro.Registry(registry), ) service.Run()Copy the code

2) client. Go

Create client Demo with GO-Micro, register with NACOS:

r := nacos.NewRegistry(func(options *registry.Options) {
        options.Addrs = addrs
    })
    service := micro.NewService(
        micro.Name("my.micro.service.client"),
        micro.Registry(r))
Copy the code

Client call:

/ / create a new Client greeter: = helloworld. NewGreeterService (serverName, service Client ()) / / call the greeter RSP, err := greeter.Hello(context.TODO(), &helloworld.HelloRequest{Name: "John"})Copy the code

Query service list:

services,err:=registry.ListServices()
Copy the code

Get a service:

service, err := registry.GetService(serverName)
Copy the code

Subscription Services:

watch, err := registry.Watch()
    for {
        result, err := watch.Next()
        if len(result.Action) > 0 {
            fmt.Println(result, err)
        }
    }
Copy the code

conclusion

It is relatively easy to use go-Micro to integrate Nacos to complete service registration and discovery. The Nacos client used by Client. Go in this project is the default configuration provided by Go-mirco.

Go-micro registry interface has a high degree of freedom, We can use context to complete the configuration of nacOS client parameters, How to use the context is set nacos client parameters may refer to: github.com/micro/go-plugins/blob/master/registry/nacos/nacos_test.go)

A link to the

  • Demo address: [github.com/sanxun0325/… github.com/sanxun0325/…
  • Go-Micro: github.com/asim/nitro
  • Nacos: Nacos. IO/useful – cn/index…
  • Nacos Nail Community Exchange Group: 30438813, 23191211(Nacos Golang Ecological Exchange Group)
  • Nacos-sdk-go Project address: github.com/nacos-group…

Author’s brief introduction

Binbin Zhang (Github account: Sanxun0325) Nacos Commiter, Sentinel-Golang Contributor, currently works in OpenJaw Micro service team. Currently, I am mainly responsible for the development of Nacos and Sentinel-Golang community-related projects, as well as the promotion and integration of Nacos in the Golang micro-service ecosystem.

“Alibaba Cloud originator focuses on micro-service, Serverless, container, Service Mesh and other technical fields, focuses on the trend of cloud native popular technology, large-scale implementation of cloud native practice, and becomes the public account that most understands cloud native developers.”