author | Zhang Binbin
Reading guide : This article mainly introduces how to use Golang Micro service framework in Ecology Go-Micro(v2) Integrate Nacos Service registration and discovery .(Go-Micro So far v3 edition , But for some reason the project has been renamed nitro For specific reasons, you can go to github View in .)
Relevant background knowledge
1. Go-Micro
Go Micro It's based on Go language-written 、 The basic framework for building microservices , Provides the core components needed for distributed development , Include RPC Communication with event drivers, etc .
Its design philosophy is 「 Pluggable 」 Plug in architecture of , Its core focuses on providing the underlying interface definition and basic tools , These underlying interfaces can be compatible with various implementations . for example Go Micro Default by consul Perform service discovery , adopt HTTP Protocol to communicate , adopt protobuf and json codec , So that you can start quickly based on the components provided out of the box , But if necessary , You can also replace the default component with other components that conform to the underlying interface definition , Such as through nacos, etcd or zookeeper Perform service discovery , This is also the advantage of plug-in architecture : The replacement of upper level components can be realized without modifying any underlying code .
1)Micro summary
Micro It's a microservice toolkit , Include :
- API
Provide and will HTTP The request is routed to the corresponding microservice API gateway . It serves as a single entry point for microservice access , take HTTP Request conversion to RPC It can also be used as a reverse proxy .
- Web
UI yes go-micro Of web edition , Allowed to pass through UI Interactive access environment . some time , It's also going to be a kind of polymeric micro Web Way of service . It contains a kind of Web Proxy mode of application . take /[name] Route to the corresponding service through the registry .Web UI The prefix “go.micro.web.”( You can configure the ) Add to the name , Look for it in the registry , Then the reverse proxy will take place .
- Sidecar
go-micro Of HTTP Interface version , It's going to be wrong Go A way of integrating applications into a microenvironment .
- Bot
Hubot Style bot, In your microservice platform , Can pass Slack,HipChat,XMPP Etc . It provides... Through messaging CLI The function of . You can add other commands to automate common operations .
- CLI
A direct command line interface to interact with your microservices , It provides a way to observe and interact with the runtime environment .
2)Go-Micro Components
Used in Go The plug-in style of writing microservices in RPC frame . It provides services for discovery , Client load balancing , code , Synchronous and asynchronous communication libraries .go-micro It's a separate library , It can be used independently of other toolkits .
go-micro It's a componentized framework , Every basic function is a interface , Easy to expand . meanwhile , Components are layered again , The upper layer provides services based on the lower layer functions , The whole structure go-micro frame .go-micro The components of the framework are :
- Registry
Provide service discovery mechanism : Resolve service name to service address . Currently supported registries are consul、etcd、 zookeeper、dns、gossip etc. .
- Selector
Selectors provide load balancing mechanisms through selection . When the client makes a request to the server , It will first query the registry of the service . This usually returns a list of running nodes representing the service . One of these selectors is used to select the nodes in the query . Calling the selector multiple times will allow the use of the balancing algorithm . The current method is circulation , Random hashes and blacklists .
- Broker
Pluggable interfaces for publishing and subscribing , Asynchronous communication between services based on message middleware , By default http The way , Message middleware is often used online , Such as Nats、Kafka、RabbitMQ and http( Used to develop ).
- Transport
Pluggable interface for point-to-point transmission of messages . The current implementation is http,rabbitmq and nats . By providing this abstraction , Transportation can be replaced seamlessly .
- Codec
The encoding of messages between services / decode .
- Plugins
Provide go-micro Of micro/go-plugins plug-in unit .
- Server
The server is the interface to build running microservices . It provides a way to provide RPC Requested method . The component is based on the above Registry/Selector/Transport/Broker Components , Provide a unified service request entry .
- Client
Provide a way to make RPC Query method to access the client of microservice . It combines the registry , Selectors , Proxy and transport . It also provides retrying , Overtime , Use context, etc . similar Server Components , It's also through Registry/Selector/Transport/Broker The component implements the lookup service 、 Load balancing 、 Synchronous communication 、 Asynchronous message and other functions .
2. Nacos
Nacos It is a dynamic service discovery that is easier to build cloud native applications 、 Configuration management and service management platform ,Nacos Born in Alibaba ConfigServer and Diamond , It's their open source implementation . It has experienced the double 11 peak flow and the test of super large-scale capacity of Alibaba economy , Precipitation of Alibaba soft load team in this field ten years of experience , It has a good guarantee in stability and functionality .
Nacos An overview of the logical architecture and its components :
Quick start
1. Go-Micro Server side
1) install protoc
Protobuf yes Protocol Buffers For short , It is Google A data description language developed by the company , And in 2008 Open source in .Protobuf When it was just open source, its positioning was similar to XML、JSON Data description language, etc , Generate code and realize the function of serializing structured data through the attached tools . We need to use protoc Generating server code .
o get github.com/golang/protobuf/protoc-gen-go
2) install Go-Micro/v2
go install github.com/micro/micro/v2
3) newly build golang project ( Server side )
- Create... In the project root directory proto Folder , For storage protobuf file
- stay proto Create under folder greeter.proto file
- The contents of the document are as follows :
Use in the server protobuf The file defines a service called Greeter The processor of , It has one HelloRequest And back to HelloResponse Of Hello Method .
syntax = "proto3";
package helloworld;
service Greeter {
rpc Hello(HelloRequest) returns (HelloResponse) {}
}
message HelloRequest {
string name = 1;
}
message HelloResponse {
string greeting = 2;
}
- Generate corresponding Go Code
protoc --micro_out=. --go_out=. proto/greeter.proto
- stay proto Under the table of contents , Generated pb.go as well as pb.micro.go Two documents
- establish server.go And run
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()
}
- stay Nacos console Can be seen in my.micro.service Successfully registered
2. Go-Micro client
- establish client.go ( For the convenience of demonstration , This article created under the same project cient.go).
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
})
// Defining services , You can pass in other optional parameters
service := micro.NewService(
micro.Name("my.micro.service.client"),
micro.Registry(r))
// Create a new client
greeter := helloworld.NewGreeterService(serverName, service.Client())
// call greeter
rsp, err := greeter.Hello(context.TODO(), &helloworld.HelloRequest{Name: "John"})
if err != nil {
fmt.Println(err)
}
// Get all the services
fmt.Println(registry.ListServices())
// Get a service
services, err := registry.GetService(serverName)
if err != nil {
fmt.Println(err)
}
// Listener Service
watch, 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)
}
}
}
- Running client , stay nacos console You can see that the client service is also registered with nacos in .
- server.go The call log is printed in the console of .
3. Go-Micro Integrate Nacos Functional specifications
1)server.go
Server side : Use go-micro Create server Demo, And register to the 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()
2)client.go
Use go-micro Create client Demo , Sign up to nacos :
r := nacos.NewRegistry(func(options *registry.Options) {
options.Addrs = addrs
})
service := micro.NewService(
micro.Name("my.micro.service.client"),
micro.Registry(r))
Client calls :
// Create a new client
greeter := helloworld.NewGreeterService(serverName, service.Client())
// call greeter
rsp, err := greeter.Hello(context.TODO(), &helloworld.HelloRequest{Name: "John"})
Query service list :
services,err:=registry.ListServices()
Get a service :
service, err := registry.GetService(serverName)
A subscription service :
watch, err := registry.Watch()
for {
result, err := watch.Next()
if len(result.Action) > 0 {
fmt.Println(result, err)
}
}
summary
Use Go-Micro Integrate Nacos Completing service registration and discovery is relatively simple and easy to start with , In this project client.go The use of nacos The client is go-mirco Default configuration provided .
go-micro Of registry The interface has high degree of freedom , We can use context complete nacos Configuration of client parameters , How to use context Set up nacos Client parameters can refer to :https://github.com/micro/go-plugins/blob/master/registry/nacos/nacos_test.go)
Related links
- Demo Address :[https://github.com/sanxun0325...](https://github.com/sanxun0325...
- Go-Micro: https://github.com/asim/nitro
- Nacos: https://nacos.io/zh-cn/index.html
- Nacos Nail down community communication groups :30438813, 23191211(Nacos golang Ecological communication group )
- Nacos-SDK-Go Project address :https://github.com/nacos-group/nacos-sdk-go
Author's brief introduction
Zhang Binbin (Github account number :sanxun0325)Nacos Commiter,Sentinel-Golang Contributor, Present position OpenJaw Micro service team . Currently mainly responsible for Nacos,Sentinel-Golang Development of community related projects , as well as Nacos stay Golang Promotion and integration in micro service ecology .
“ Alibaba cloud native Focus on microservices 、Serverless、 Containers 、Service Mesh And other technical fields 、 The trend of primary popular technology of focus cloud 、 Large scale practice of cloud original , Official account of cloud developers .”