当前位置:网站首页>Go micro tutorial - Chapter 2 go micro V3 using gin and etcd
Go micro tutorial - Chapter 2 go micro V3 using gin and etcd
2022-07-04 17:03:00 【Ximu Qi】
go-micro course — Chapter two go-micro v3 Use Gin、Etcd
- Preface
- One 、 start-up Etcd colony
- Two 、 Create projects and install related dependencies
- 3、 ... and 、 Development projects
- ※ Four 、 Use consul Register as a registry service
- 5、 ... and 、 Use etcd As a registry
Preface
Be careful
: This article uses Go Version is go1.17.6
Use 1.18.x
Version or other versions always encounter various problems during operation , For example, dependent download exceptions . Of course, it may also be the problem of my computer .
Reference documents :go The service of go-micro v3+gin
One 、 start-up Etcd colony
In the use of Etcd As a registration center, you need to have Etcd Node or Etcd colony ,Etcd Installation, configuration and startup of the cluster , See :Etcd course — Chapter four Etcd Cluster security configuration .
Two 、 Create projects and install related dependencies
Be careful
:2.3 To 2.6 At the same time after the steps are executed ${GOPATH}\bin
Lower generation exe file .
2.1 Create project
The project name created in this article is micro-demo
2.2 Initialize project
go mod init micro-demo
2.3 install proto
see :Go — Related dependencies correspond to exe 1、protobuf
2.4 install protoc-gen-go
go get github.com/golang/protobuf/protoc-gen-go
2.5 install protoc-gen-micro
Be careful
: It's installation asim
Instead of micro
Under the , because micro
The next one can't be downloaded , This is also go micro 3.0 frame .
go get github.com/asim/go-micro/cmd/protoc-gen-micro/v3
2.6 install micro v3 Building tools
- Need to use Micro 3.0 Of micro Tools , It is mainly used for rapid construction micro project , But do not use this configuration , Use the following 2 Of
go install github.com/micro/micro/[email protected]
- download go micro 3.0 library , The lower library has no upper micro Building tools
go get github.com/asim/go-micro/v3
2.7 install gin
go get -u github.com/gin-gonic/gin
3、 ... and 、 Development projects
3.1 establish web
modular
stay micro-demo
Create web
Folder
3.2 Get into web
Folder
establish main.go
file
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
const addr = ":8080"
func Index(c *gin.Context) {
c.JSON(http.StatusOK, map[string]interface{}{
"message": "index Successful visit ",
})
}
func main() {
r := gin.Default()
r.Handle("GET", "/", Index)
if err := r.Run(addr); err != nil {
fmt.Println("err")
}
}
And then execute go run .
Or in Goland In the implementation of main function , start-up web service .
After successful startup , Access in browser http://127.0.0.1, Get the following response :
// 20220704103107
// http://localhost:8080/
{
"message": "index Successful visit "
}
3.3 establish services modular
stay micro-demo
perform micro new services
command , Create a back-end service module .
3.4 Delete go.mod file
Delete services
Under the module of go.mod
file , Unified use micro-demo
Under the go.mod
.
3.5 according to proto Generate pb file
3.5.1 modify services.proto
The main thing is to modify go_package
Specify generation pb The path of the document , Here is the general ./ Change it to ../
that will do .
syntax = "proto3";
package services;
//option go_package = "./proto;services";
// take ./ Change it to ../
option go_package = "../proto;services";
service Services {
rpc Call(Request) returns (Response) {}
rpc Stream(StreamingRequest) returns (stream StreamingResponse) {}
rpc PingPong(stream Ping) returns (stream Pong) {}
}
message Message {
string say = 1;
}
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;
}
3.5.2 Generate pb file
Enter into micro-demo\services\proto>
. Execute build command :
protoc --proto_path=. --micro_out=. --go_out=. *.proto
After execution, you can micro-demo\services\proto>
See the generated services.pb.go
and services.pb.micro.go
file .
3.6 modify handler/services.go file
modify micro-demo\services\handler>
Under the services.go
It is mainly modified and introduced pb file location .
import (
"context"
log "github.com/micro/micro/v3/service/logger"
//services "services/proto"
services "micro-demo/services/proto"
)
3.7 modify services/main.go file
package main
import (
// modify 1
//"services/handler"
"micro-demo/services/handler"
//pb "services/proto"
pb "micro-demo/services/proto"
// modify 2
//"github.com/micro/micro/v3/service"
//"github.com/micro/micro/v3/service/logger"
service "github.com/asim/go-micro/v3"
"github.com/asim/go-micro/v3/logger"
)
func main() {
// Create service
// modify 3
srv := service.NewService( // service.New
service.Name("services01"),
service.Version("latest"),
)
// Register handler
// modify 4
_ = pb.RegisterServicesHandler(srv.Server(), new(handler.Services))
// Run service
if err := srv.Run(); err != nil {
logger.Fatal(err)
}
}
And then execute go run .
Or in Goland In the implementation of main function , The startup name is services01
Service for .
After successful startup , Console display content :
API server listening at: 127.0.0.1:51514
2022-07-04 11:26:04 [email protected]/service.go:206 level=info Starting [service] services01
2022-07-04 11:26:04 file=server/rpc_server.go:820 level=info Transport [http] Listening on [::]:51521
2022-07-04 11:26:04 file=server/rpc_server.go:840 level=info Broker [http] Connected to 127.0.0.1:51522
2022-07-04 11:26:04 file=server/rpc_server.go:654 level=info Registry [mdns] Registering node: services01-ea97f1e6-f4b4-4431-8087-d41e430979ef
3.8 adopt web Module call services Module Services
3.8.1 establish web/handler/services01Handler.go
file
package handler
import (
"github.com/asim/go-micro/v3"
"github.com/gin-gonic/gin"
servicepb "micro-demo/services/proto"
"net/http"
)
func Index(c *gin.Context) {
c.JSON(http.StatusOK, map[string]interface{}{
"message": "index",
})
}
func ServiceOne(c *gin.Context) {
service := micro.NewService()
service.Init()
// Create a microservice client
client := servicepb.NewServicesService("services01", service.Client())
// Call the service
rsp, err := client.Call(c, &servicepb.Request{
Name: c.Query("key"),
})
if err != nil {
c.JSON(200, gin.H{"code": 500, "msg": err.Error()})
return
}
c.JSON(200, gin.H{"code": 200, "msg": rsp.Msg})
}
3.8.2 modify web/main.go file
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"micro-demo/web/handler"
"net/http"
)
const addr = ":8080"
func Index(c *gin.Context) {
c.JSON(http.StatusOK, map[string]interface{}{
"message": "index Successful visit ",
})
}
func main() {
r := gin.Default()
r.Handle("GET", "/", Index)
r.Handle("GET", "/service-req", handler.ServiceOne)
if err := r.Run(addr); err != nil {
fmt.Println("err")
}
}
And then execute go run .
Or in Goland In the implementation of main function , Restart web service .
Startup results :
[GIN-debug] GET / --> main.Index (3 handlers)
[GIN-debug] GET /service-req --> micro-demo/web/handler.ServiceOne (3 handlers)
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
[GIN-debug] Listening and serving HTTP on :8080
Browser access http://127.0.0.1:8080/service-req?key= ha-ha
, Get the following response :
// 20220704113801
// http://127.0.0.1:8080/service-req?key=%E5%93%88%E5%93%88
{
"code": 200,
"msg": "Hello ha-ha "
}
※ Four 、 Use consul Register as a registry service
Be careful
: Use consul As a registration center, the registration service has not been practiced , There may be problems .
4.1 Installation configuration consul
The installation configuration is preferred consul service , Independent installation , Or use docker Can be installed .
start-up consul after , Use browser access http://192.168.1.224:8500
4.2 Project joining consul package
go get -u github.com/asim/go-micro/plugins/registry/consul/v3
4.3 modify services/main.go
Major modifications or additions consul 1
、consul 2
、consul 3
package main
import (
"micro-demo/services/handler"
pb "micro-demo/services/proto"
service "github.com/asim/go-micro/v3"
"github.com/asim/go-micro/v3/logger"
//consul 1
"github.com/asim/go-micro/plugins/registry/consul/v3"
"github.com/asim/go-micro/v3/registry"
)
//consul 2
const (
ServerName = "services01"
ConsulAddr = "192.168.1.224:8500"
)
func main() {
// consul 3
consulReg := consul.NewRegistry(
registry.Addrs(ConsulAddr),
)
srv := service.NewService(
service.Name(ServerName), // Service name
service.Registry(consulReg),// Registry Center
)
// Register handler
_ = pb.RegisterServicesHandler(srv.Server(), new(handler.Services))
// Run service
if err := srv.Run(); err != nil {
logger.Fatal(err)
}
}
perform go run ., Restart services The name of the module is services01 Service for .
4.4 modify web/handler/services01Handler.go
Major modifications or additions consul 1
、consul 2
package handler
import (
"github.com/asim/go-micro/v3"
"github.com/gin-gonic/gin"
servicepb "micro-demo/services/proto"
"net/http"
//consul 1
"github.com/asim/go-micro/plugins/registry/consul/v3"
"github.com/asim/go-micro/v3/registry
)
func Index(c *gin.Context) {
c.JSON(http.StatusOK, map[string]interface{}{
"message": "index",
})
}
func ServiceOne(c *gin.Context) {
//consul 2
consulReg := consul.NewRegistry(
registry.Addrs("192.168.1.224:8500"),
)
service := micro.NewService(
micro.Registry(consulReg), // Set up a registry
)
service.Init()
// Create a microservice client
client := servicepb.NewServicesService("services01", service.Client())
// Call the service
rsp, err := client.Call(c, &servicepb.Request{
Name: c.Query("key"),
})
if err != nil {
c.JSON(200, gin.H{"code": 500, "msg": err.Error()})
return
}
c.JSON(200, gin.H{"code": 200, "msg": rsp.Msg})
}
perform go run ., restart web.
5、 ... and 、 Use etcd As a registry
5.1 Project joining etcd package
go get -u "github.com/asim/go-micro/plugins/registry/etcd/v3"
5.2 modify services/main.go
package main
import (
"micro-demo/services/handler"
pb "micro-demo/services/proto"
service "github.com/asim/go-micro/v3"
"github.com/asim/go-micro/v3/logger"
//etcd 1
"github.com/asim/go-micro/plugins/registry/etcd/v3"
"github.com/asim/go-micro/v3/registry"
)
//etcd 2
const (
ServerName = "services01"
EtcdAddr = "192.168.1.221:2379"
)
func main() {
//etcd 3
etcdReg := etcd.NewRegistry(
registry.Addrs(EtcdAddr),
)
srv := service.NewService(
service.Name(ServerName), // Service name
service.Registry(etcdReg), // Registry Center
)
// Register handler
_ = pb.RegisterServicesHandler(srv.Server(), new(handler.Services))
// Run service
if err := srv.Run(); err != nil {
logger.Fatal(err)
}
}
5.3 modify web/handler/services01Handler.go
package handler
import (
"github.com/asim/go-micro/v3"
"github.com/gin-gonic/gin"
servicepb "micro-demo/services/proto"
"net/http"
//etcd 1
"github.com/asim/go-micro/plugins/registry/etcd/v3"
"github.com/asim/go-micro/v3/registry"
)
func Index(c *gin.Context) {
c.JSON(http.StatusOK, map[string]interface{}{
"message": "index",
})
}
func ServiceOne(c *gin.Context) {
// etcd 2
etcdReg := etcd.NewRegistry(
registry.Addrs("192.168.1.221:2379"),
)
service := micro.NewService(
micro.Registry(etcdReg), // Set up a registry
)
service.Init()
// Create a microservice client
client := servicepb.NewServicesService("services01", service.Client())
// Call the service
rsp, err := client.Call(c, &servicepb.Request{
Name: c.Query("key"),
})
if err != nil {
c.JSON(200, gin.H{"code": 500, "msg": err.Error()})
return
}
c.JSON(200, gin.H{"code": 200, "msg": rsp.Msg})
}
perform go run ., restart web, And then send http://127.0.0.1:8080/service-req?key= ha-ha
, Return results :
// 20220704132910
// http://127.0.0.1:8080/service-req?key=%E5%93%88%E5%93%88
{
"code": 200,
"msg": "Hello ha-ha "
}
5.4 see etcd Service registration in
边栏推荐
- Capvision Rongying's prospectus in Hong Kong was "invalid": it was strictly questioned by the CSRC and required supplementary disclosure
- PyTorch深度学习快速入门教程
- Four point probe Industry Research Report - market status analysis and development prospect prediction
- Go语言循环语句(第10课下)
- [North Asia data recovery] a database data recovery case where the disk on which the database is located is unrecognized due to the RAID disk failure of HP DL380 server
- Understand asp Net core - Authentication Based on jwtbearer
- ~88 running people practice
- Detailed process of DC-2 range construction and penetration practice (DC range Series)
- Practice: fabric user certificate revocation operation process
- DIY a low-cost multi-functional dot matrix clock!
猜你喜欢
overflow:auto与felx结合的用法
C# 更加优质的操作MongoDB数据库
《吐血整理》保姆级系列教程-玩转Fiddler抓包教程(2)-初识Fiddler让你理性认识一下
C# 服务器日志模块
智慧物流園區供應鏈管理系統解决方案:數智化供應鏈賦能物流運輸行業供應鏈新模式
Blood spitting finishing nanny level series tutorial - play Fiddler bag grabbing tutorial (2) - first meet fiddler, let you have a rational understanding
GO开发:如何利用Go单例模式保障流媒体高并发的安全性?
Detailed process of DC-2 range construction and penetration practice (DC range Series)
Can you really use MySQL explain?
建筑建材行业经销商协同系统解决方案:赋能企业构建核心竞争力
随机推荐
Application and Optimization Practice of redis in vivo push platform
51 single chip microcomputer temperature alarm based on WiFi control
照明行业S2B2B解决方案:高效赋能产业供应链,提升企业经济效益
Years of training, towards Kata 3.0! Enter the safe container experience out of the box | dragon lizard Technology
Research Report on market supply and demand and strategy of China's Sodium Tetraphenylborate (cas+143-66-8) industry
Sql实现Split
How to contribute to the source code of ongdb core project
Can you really use MySQL explain?
安信证券排名 网上开户安全吗
Yanwen logistics plans to be listed on Shenzhen Stock Exchange: it is mainly engaged in international express business, and its gross profit margin is far lower than the industry level
How can programmers improve the speed of code writing?
Opencv learning -- geometric transformation of image processing
Smart Logistics Park supply chain management system solution: digital intelligent supply chain enables a new supply chain model for the logistics transportation industry
go-micro教程 — 第二章 go-micro v3 使用Gin、Etcd
中位数与次序统计量
Four point probe Industry Research Report - market status analysis and development prospect prediction
. Net applications consider x64 generation
Statistical learning: logistic regression and cross entropy loss (pytoch Implementation)
System.currentTimeMillis() 和 System.nanoTime() 哪个更快?别用错了!
实战:fabric 用户证书吊销操作流程