当前位置:网站首页>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
边栏推荐
- System.currentTimeMillis() 和 System.nanoTime() 哪个更快?别用错了!
- 【云原生】服务网格是什么“格”?
- Application of clock wheel in RPC
- Visual Studio 2019 (LocalDB)MSSQLLocalDB SQL Server 2014 数据库版本为852无法打开,此服务器支持782
- 中位数与次序统计量
- 基于wifi控制的51单片机温度报警器
- C# 更加优质的操作MongoDB数据库
- China Indonesia adhesive market trend report, technological innovation and market forecast
- 新的职业已经出现,怎么能够停滞不前 ,人社部公布建筑新职业
- [Acwing] 58周赛 4490. 染色
猜你喜欢
[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
祝贺Artefact首席数据科学家张鹏飞先生荣获 Campaign Asia Tech MVP 2022
建筑建材行业经销商协同系统解决方案:赋能企业构建核心竞争力
电子元器件B2B商城系统开发:赋能企业构建进销存标准化流程实例
容器环境minor gc异常频繁分析
S2b2b solution for lighting industry: efficiently enable the industrial supply chain and improve the economic benefits of enterprises
NoSQL之readis配置与优化(终章)
Solution du système de gestion de la chaîne d'approvisionnement du parc logistique intelligent
Smart Logistics Park supply chain management system solution: digital intelligent supply chain enables a new supply chain model for the logistics transportation industry
Transformer中position encoding实践
随机推荐
智慧物流園區供應鏈管理系統解决方案:數智化供應鏈賦能物流運輸行業供應鏈新模式
一图看懂ThreadLocal
tp配置多数据库
Capvision Rongying's prospectus in Hong Kong was "invalid": it was strictly questioned by the CSRC and required supplementary disclosure
ECCV 2022放榜了:1629篇论文中选,录用率不到20%
FIREBIRD使用经验总结
Implement graph data construction task based on check point
程序员怎么才能提高代码编写速度?
Accounting regulations and professional ethics [8]
从数数开始
力扣今日题-1200. 最小绝对差
Application and Optimization Practice of redis in vivo push platform
SQL implements split
leetcode刷题目录总结
Start by counting
对人胜率84%,DeepMind AI首次在西洋陆军棋中达到人类专家水平
Is it safe to open an account online
[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
新的职业已经出现,怎么能够停滞不前 ,人社部公布建筑新职业
Object.keys()的用法