How to set up go-micro development environment

藏色散人
Release: 2020-08-12 13:58:50
forward
3021 people have browsed it

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
Copy after login

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
Copy after login

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"
Copy after login

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
Copy after login

Test it

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

micro web
Copy after login
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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;}
Copy after login

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)
    }}
Copy after login

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)}
Copy after login

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)
Copy after login

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
Copy after login

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
Copy after login

You can use micro to view the currently running microservices

micro list services
Copy after login

You can also view it on the web side

micro web
Copy after login
Copy after login

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

$ micro list services
go.micro.web
greeter
Copy after login

Test

Now you can run the client to test it

go run client.go greeter.pb.go greeter.pb.micro.go
Copy after login

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]
Copy after login

Check the service information

micro get service greeter
Copy after login
$ 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                                                                                        
}
Copy after login

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
Copy after login

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
Copy after login

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!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template