当前位置:网站首页>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
边栏推荐
- "Cannot initialize Photoshop because the temporary storage disk is full" graphic solution
- Why do you say that the maximum single table of MySQL database is 20million? Based on what?
- China tall oil fatty acid market trend report, technical dynamic innovation and market forecast
- Go development: how to use go singleton mode to ensure the security of high concurrency of streaming media?
- 照明行业S2B2B解决方案:高效赋能产业供应链,提升企业经济效益
- How to contribute to the source code of ongdb core project
- 智慧物流园区供应链管理系统解决方案:数智化供应链赋能物流运输行业供应链新模式
- The test experience "tortured" by the PMP test is worth your review
- System. Currenttimemillis() and system Nanotime (), which is faster? Don't use it wrong!
- C implementation defines a set of intermediate SQL statements that can be executed across libraries
猜你喜欢

2022PMP考试基本情况详情了解

L1-072 scratch lottery
![[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](/img/79/3fab19045e1ab2f5163033afaa4309.jpg)
[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

~89 deformation translation
Can you really use MySQL explain?
Why do you say that the maximum single table of MySQL database is 20million? Based on what?

Years of training, towards Kata 3.0! Enter the safe container experience out of the box | dragon lizard Technology

2022年国内云管平台厂商哪家好?为什么?

Go development: how to use go singleton mode to ensure the security of high concurrency of streaming media?

Smart Logistics Park supply chain management system solution: digital intelligent supply chain enables a new supply chain model for the logistics transportation industry
随机推荐
Principle and general steps of SQL injection
Accounting regulations and professional ethics [9]
基于check-point实现图数据构建任务
Object.keys()的用法
Understand ThreadLocal in one picture
高度剩余法
VMware Tools和open-vm-tools的安装与使用:解决虚拟机不全屏和无法传输文件的问题
Go language loop statement (under Lesson 10)
js中的数组筛选fliter
.Net 应用考虑x64生成
[glide] cache implementation - memory and disk cache
Visual Studio 2019 (LocalDB)MSSQLLocalDB SQL Server 2014 数据库版本为852无法打开,此服务器支持782
Hair and fuzz interceptor Industry Research Report - market status analysis and development prospect forecast
Solution du système de gestion de la chaîne d'approvisionnement du parc logistique intelligent
Four point probe Industry Research Report - market status analysis and development prospect prediction
Understand asp Net core - Authentication Based on jwtbearer
Capvision Rongying's prospectus in Hong Kong was "invalid": it was strictly questioned by the CSRC and required supplementary disclosure
[Acwing] 58周赛 4489. 最长子序列
C implementation defines a set of intermediate SQL statements that can be executed across libraries
C# 更加优质的操作MongoDB数据库