Home  >  Article  >  Backend Development  >  How to set up go-micro development environment

How to set up go-micro development environment

藏色散人
藏色散人forward
2020-08-12 13:58:503020browse

The following column will introduce you to the method of setting up the go-micro development environment from the Golang Tutorial column. I hope it will be helpful to friends in need!

How to set up go-micro development environment

#Recently, because I have to use go-micro, I am learning about microservices. This article records the construction process of micro.

Installation environment

micro provides a runtime, which needs to be installed before using go-micro. There are several ways to install it

Source code

go get github.com/micro/micro/v2

I can’t install it this way. It’s not due to the network. I don’t know where the conflict is. . .

docker

docker pull micro/micro

Binary

# MacOS
curl -fsSL https://raw.githubusercontent.com/micro/micro/master/scripts/install.sh | /bin/bash

# Linux
wget -q  https://raw.githubusercontent.com/micro/micro/master/scripts/install.sh -O - | /bin/bash

# Windows
powershell -Command "iwr -useb https://raw.githubusercontent.com/micro/micro/master/scripts/install.ps1 | iex"

It is recommended to use this method to download and install, compile A good binary package can be used directly by adding it to the environment variable. If you don’t want to use a script to install, you can download it from the release page of github

https://github.com/micro/micro/releases

Test it

Now that the micro is installed, let’s test it.

micro web

Output

$ micro web2020-07-05 04:24:16  file=http/http.go:90 level=info service=web HTTP API Listening on [::]:80822020-07-05 04:24:16  file=v2@v2.9.1/service.go:200 level=info service=web Starting [service] go.micro.web2020-07-05 04:24:16  file=grpc/grpc.go:864 level=info service=web Server [grpc] Listening on [::]:264492020-07-05 04:24:16  file=grpc/grpc.go:697 level=info service=web Registry [mdns] Registering node: go.micro.web-b76a12a1-5226-429f-9633-ce304f179657

Now visit localhost:8082 to view the micro’s web page.

Installing protoc

protoc is the compiler of protobuf, and protobuf is a format used to transmit data, similar to json and xml.
protoc download address

https://github.com/protocolbuffers/protobuf/releases

After downloading, there is a protoc executable file in the bin folder. Add this to the environment variable. (You can just put it directly in a folder that has added environment variables. This can avoid the computer being filled with various environment variables, and putting commonly used tools in a folder is also convenient for management)

Recommended: "go Language"

There is also protoc-gen-go that needs to be put in. You can download it in the following way.

go get -u github.com/golang/protobuf/proto
go get -u github.com/golang/protobuf/protoc-gen-go

example

Now let’s write a demo to practice.

There are three files in total, server.go, client.go, greeter.proto

##greeter.proto
syntax = "proto3";package protos;service Greeter {
    rpc Hello (Request) returns (Response){};}message Request {
    string name = 1;}message Response {
    string greeting = 2;}

server.go
package mainimport (
    "context"
    "fmt"
    "github.com/micro/go-micro/v2")type Greeter struct {}func (g *Greeter) Hello(context context.Context, req *Request, rsp *Response) error {
    rsp.Greeting = "Hello " + req.Name    return nil}func main() {
    service := micro.NewService(
        micro.Name("greeter"),
    )
    service.Init()

    err := RegisterGreeterHandler(service.Server(), new(Greeter))
    if err != nil {
        fmt.Println(err)
    }

    if err := service.Run(); err != nil {
        fmt.Println(err)
    }}

client.go
package mainimport (
    "context"
    "fmt"
    "github.com/micro/go-micro/v2")func main() {
    service := micro.NewService(micro.Name("greeter.client"))
    service.Init()

    greeter := NewGreeterService("greeter", service.Client())
    rsp, err := greeter.Hello(context.TODO(), &Request{Name: "Zaun pianist"})
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(rsp.Greeting)}

Highly recommended Use go mod to manage dependencies. The project updates very quickly. Many tutorials on Baidu no longer work. There are various errors during the installation process

This is my mod file

module hello

go 1.14require (
    github.com/golang/protobuf v1.4.0
    github.com/micro/go-micro/v2 v2.9.1
    google.golang.org/protobuf v1.22.0)

Note that my greeter.proto, server.go, and client.go files are placed in the same folder

Compile greeter.proto
protoc --micro_out=. --go_out=. greeter.proto

After compilation is completed, two go source code files will be generated:

  • greeter.pb.go
  • greeter.pb.micro .go

Run

Now you can run the server, because the client and server are placed in the same folder, that is, the same In the package, both have main functions, so

go run ./ cannot be used. As for why the other two are added, this is a requirement of the go language compiler. You must specify what is needed for compilation. document.

go run server.go greeter.pb.go greeter.pb.micro.go

You can use micro to view the currently running microservices

micro list services

You can also view it on the web side

micro web

If there is no error, you can see that the service has been Registration successful.

$ micro list services
go.micro.web
greeter

Test

Now you can run the client to test it

go run client.go greeter.pb.go greeter.pb.micro.go

I had a problem during the test, the service has been registered , but when the client calls it, it returns missing

{"id":"go.micro.client","code":408,"detail":"context deadline exceeded","status":"Request Timeout"}panic: runtime error: invalid memory address or nil pointer dereference[signal 0xc0000005 code=0x0 addr=0x28 pc=0xeef454]

Check the service information

micro get service greeter
$ micro get service greeter                                                                                    
service  greeter                                                                                               

version latest                                                                                                 

ID      Address Metadata                                                                                       
greeter-5d86321e-86f2-41a6-8230-f015466bf791    10.198.75.60:51395      broker=http,protocol=grpc,registry=mdns,server=grpc,transport=grpc                                                                                    

Endpoint: Greeter.Hello                                                                                        

Request: {                                                                                                     
        message_state MessageState {                                                                           
                no_unkeyed_literals NoUnkeyedLiterals                                                          
                do_not_compare DoNotCompare                                                                    
                do_not_copy DoNotCopy                                                                          
                message_info MessageInfo                                                                       
        }                                                                                                      
        int32 int32                                                                                            
        unknown_fields []uint8                                                                                 
        name string                                                                                            
}                                                                                                              Response: {                                                                                                    
        message_state MessageState {                                                                           
                no_unkeyed_literals NoUnkeyedLiterals                                                          
                do_not_compare DoNotCompare                                                                    
                do_not_copy DoNotCopy                                                                          
                message_info MessageInfo                                                                       
        }                                                                                                      
        int32 int32                                                                                            
        unknown_fields []uint8                                                                                 
        greeting string                                                                                        
}

Pay attention to the IP address inside, it is registered to

10.198.xx , is this why an error is reported? ? ? Therefore, when registering the service, specify the IP address

go run server.go greeter.pb.go greeter.pb.micro.go --server_address=localhost:8888

There will be no error if you call it with client at this time.

$ go run client.go greeter.pb.go greeter.pb.micro.go
Hello Zaun pianist

The above is the detailed content of How to set up go-micro development environment. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete