Technology stack and environment
Technology stack
Go 1.16 GO-Micro V3 Micro V3 Protobuf v3 GPRC ConsulCopy the code
The environment
Mac 11.2.2
Liunx centeros 8
Copy the code
instructions
Go 1.17.1
Go 1.17.1 Currently (2021.9.10) Go-Micro conflicts with Consul
Go – micro micro difference
In v3, micro and Go-Micro are separated, micro belongs to the company and Go-Micro belongs to ASIM.
Micro aims to become a cloud service
Go-micro is a micro service
We’ll just use Go-Micro here, micro just helps us generate the framework quickly
Environmental installation
Install the go. 16
Go to the official website (golang.google.cn/dl/) to download the PKG package and click install
Configuring environment Variables
Open the configuration
open ~/.bash_profile
Copy the code
Write the configuration
Export GOROOT=/usr/local/go # GOPATH Export GOPATH=/Users/Desktop/go export GOBIN=$GOROOT/bin export PATH=$PATH:$GOBINCopy the code
save
source ~/.bash_profile
Copy the code
GOROOT and GOPATH
GOROOT is the root of Golang
GOPATH is your project directory
There are three bin PKG SRC files in GOPATH
Bin is the directory where you store your binaries. PKG is the third-party library where you store your downloads. SRC is where you write your codeCopy the code
Install the protobuf
Protobuf3 download address (github.com/protocolbuf…)
Decompress the package and go to the directory
CD protobuf - 3.7.0 /Copy the code
Setting the compile directory
./configure --prefix=/usr/local/protobuf
Copy the code
The installation
make
make install
Copy the code
Open the configuration
open ~/.bash_profile
Copy the code
Write the configuration
# protobuf
export PROTOBUF=/usr/local/protobuf
export PATH=$PROTOBUF/bin:$PATH
Copy the code
save
source ~/.bash_profile
Copy the code
Test installation results
protoc --version
Copy the code
Install protoc – gen – go
go get github.com/micro/micro/v3/cmd/protoc-gen-micro
Copy the code
See it in your GOPATH bin
Install protoc – gen – micro
go get github.com/micro/micro/v3/cmd/protoc-gen-micro
Copy the code
See it in your GOPATH bin
Install the micro
go get github.com/micro/micro/v3
Copy the code
See it in your GOPATH bin
Install the consul
I’m using docker installation here
docker pull consul
Copy the code
run
Docker run -d -p 85:8500 -h consul --name consul agent-dev-client 0.0.0.0 -uiCopy the code
Enter http://127.0.0.1:8500/ui to view the admin background
Start coding
Start the micro
micro server
Copy the code
The login
Micro login // Default account admin // Default password microCopy the code
Creating the Micro Service
// Testdemo is your micro service name micro new testdemoCopy the code
The directory structure
Proto file description
// proto version syntax = "proto3"; // Package name package testdemo; // package location option go_package = "./proto; testdemo"; Service Testdemo {RPC Call(Request) returns (Response) {} RPC Stream(StreamingRequest) Returns (stream StreamingResponse) {} RPC PingPong(stream Ping) {}} // struct, model // Message {string say1 = 1; string say2 = 2; string say3 = 3; } message Request { string name = 1; } message Response { string msg = 1; } message StreamingRequest { int64 count = 1; } message StreamingResponse { int64 count = 1; } message Ping { int64 stroke = 1; } message Pong { int64 stroke = 1; }Copy the code
Write the proto
I’m going to save this because I just want to write a simple demo
syntax = "proto3"; package testdemo; option go_package = "./proto; testdemo"; service Testdemo { rpc Call(Request) returns (Response) {} } message Request { string name = 1; } message Response { string msg = 1; }Copy the code
CD./ project make protoCopy the code
Generate three files
Enter the testdemo. Pb. Micro. Go
Modify the reference
The original
import (
fmt "fmt"
proto "github.com/golang/protobuf/proto"
math "math"
)
import (
context "context"
client "github.com/micro/go-micro/client"
server "github.com/micro/go-micro/server"
Copy the code
After modification, change micro to Go-micro
import (
fmt "fmt"
proto "github.com/golang/protobuf/proto"
math "math"
)
import (
context "context"
client "github.com/asim/go-micro/v3/client"
server "github.com/asim/go-micro/v3/server"
)
Copy the code
Enter the handler
The handler file contains the name of the protoc function
Modify the file
The original
package handler import ( "context" log "github.com/micro/micro/v3/service/logger" testdemo "testdemo/proto" ) type Testdemo struct{} // Call is a single request handler called via client.Call or the generated client code func (e *Testdemo) Call(ctx context.Context, req *testdemo.Request, rsp *testdemo.Response) error { log.Info("Received Testdemo.Call request") rsp.Msg = "Hello " + req.Name return nil } // Stream is a server side stream handler called via client.Stream or the generated client code func (e *Testdemo) Stream(ctx context.Context, req *testdemo.StreamingRequest, stream testdemo.Testdemo_StreamStream) error { log.Infof("Received Testdemo.Stream request with count: %d", req.Count) for i := 0; i < int(req.Count); i++ { log.Infof("Responding: %d", i) if err := stream.Send(&testdemo.StreamingResponse{ Count: int64(i), }); err ! = nil { return err } } return nil } // PingPong is a bidirectional stream handler called via client.Stream or the generated client code func (e *Testdemo) PingPong(ctx context.Context, stream testdemo.Testdemo_PingPongStream) error { for { req, err := stream.Recv() if err ! = nil { return err } log.Infof("Got ping %v", req.Stroke) if err := stream.Send(&testdemo.Pong{Stroke: req.Stroke}); err ! = nil { return err } } }Copy the code
After modification, delete redundant functions
package handler
import (
"context"
testdemo "testdemo/proto"
)
type Testdemo struct{}
// Call is a single request handler called via client.Call or the generated client code
func (e *Testdemo) Call(ctx context.Context, req *testdemo.Request, rsp *testdemo.Response) error {
fmt.Println(req, rsp)
rsp.Msg = req.Name
return nil
}
Copy the code
Enter the main. Go
package main import ( "fmt" "github.com/asim/go-micro/plugins/registry/consul/v3" "github.com/asim/go-micro/v3" "ConsulReg := consul.newregistry () // Create service (consulReg := consul.newregistry ()) SRV := micro.NewService(micro.Address("0.0.0.0:9001"), ConsulReg (consulReg); // Add consul to consul micro.version ("1.0.0"); // Add consul micro.version ("1.0.0"); / / version) / / Register handler pb. RegisterTestdemoHandler (SRV) Server (), new(handler.Microdemo)) // Run service if err := srv.Run(); err ! Println(" Failed to start =",err)}} = nil {// logger.fatal (err) fmt.Println(" Failed to start =",err)}}Copy the code
Creating a Web service
- Create a microWebDemo directory
- Create the main. Go
- Pull micor’s ProTO project to the past (it will be necessary to modify proTO again in the future)
Enter the main. Go
I’m using the GIN framework here
package main import ( "context" "fmt" "github.com/asim/go-micro/plugins/registry/consul/v3" "github.com/asim/go-micro/v3" "github.com/gin-gonic/gin" pb "Microwebdemo /proto" "net/ HTTP") func main() {// Initialize the route Router := gin.Default() // Group R1 := router.Group(" API /") {r1.get ("/demo",demo) r1.get ("/ Hahn ", Hahn)} // Start the operation Router.run (" 0.0.0.00:9002 ")} func demo(CTX *gin.Context) {consulReg := consul.newregistry () consulService := micro.NewService( micro.Registry(consulReg), NewTestdemoService("Microdemo", consulservice.client ()); // Conn.consulservice.client (); err := microClient.Call(context.TODO(), &pb.Request{Name: "zzr"}) if err ! = nil {FMT.Println(" Remote service not found..." ) return} res := make(map[string]interface{}) res["errno"] = 200 res["errmsg"] = "success" res["data"] = resp The browser CTX. JSON (HTTP StatusOK, Res)} func Hahn (CTX *gin.Context) {resp := make(map[string]interface{}) resp["errno"] = 200 resp["errmsg"] = "success" resp["data"] = "data" ctx.JSON(http.StatusOK, resp) }Copy the code
Error: Package XXX is not in GOROOT or GOPATH
If this comes up
cd ./microwebdemo
go mod init
go mod tidy
Copy the code
Run the project
Start Web and Micro
I use Goland Idea
Just run
Docker start the consul
First startup
Docker run -d -p 85:8500 -h consul --name consul agent-dev-client 0.0.0.0 -uiCopy the code
Second start
Docker ps -a // Start docker XXX docker start XXX // Close docker XXX docker stop XXXCopy the code
test
Simple gin
http://127.0.0.1:9002/api/hahn
Copy the code
micro
http://127.0.0.1:9002/api/demo
Copy the code
Liunx Docker-compose deployment project
Package the Go file
Enter micro and Web respectively
Package the Liunx environment
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build main.go
Copy the code
Change the two main names to MicrowebDemo and microdemo
Docker packaging
Enter micro and Web respectively
Write Dockerfile
The FROM alpine: latest RUN apk - no - cache add ca - certificates WORKDIR/XXXX/go/SRC/microwebdemo / # you microwebdemo path go packaging applications COPY microwebdemo ./ CMD ["./microwebdemo"] FROM alpine:latest RUN apk --no-cache add ca-certificates WORKDIR COPY microdemo./ CMD ["./microdemo"]Copy the code
docker build -t microwebdemo .
docker build -t microdemo .
Copy the code
Docker Images view images
Upload the image
Enter micro and Web respectively
Packaging image
docker image save microdemo > microdemo.tar
docker image save microwebdemo > microwebdemo.tar
Copy the code
Upload microdemo.tar and MicrowebDemo. tar to liunx
Linux configuration
Turn tar into a mirror image
docker load --input microdemo.tar
docker load --input microwebdemo.tar
Copy the code
Docker Images view images
Docker – compose configuration
Docker-compose version version: '3.5' Services: # consul mirroring consul: image: consul Network_mode: host The communication mode is host command: Agent-dev-client 0.0.0.0 -ui # enable consul developer mode # microdemo image microdemo: image: microdemo container_name: Microdemo network_mode: host # MicrowebDemo: image: microwebDemo container_name: microwebdemo network_mode: hostCopy the code
Start the service
docker-compose up
Copy the code
successful
Docker and docker-compose commands
docker
Docker images # docker images # docker images # docker images # docker images # docker images # docker images # docker images # docker images # docker images # docker images # docker images # docker images # docker images # docker images # docker images # docker images Same mirror image. Docker PS-A will show multiple images of the same image, Docker run XXX # start XXX # stop docker ps-a Docker rm XXX docker rm XXX docker rm XXX docker rm XXXCopy the code
docker-compose
Docker-compose can start docker-compose up // start docker-compose up // stop docker-compose downCopy the code