当前位置:网站首页>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
边栏推荐
- Transformer中position encoding实践
- China's roof ladder market trend report, technological innovation and market forecast
- Application and Optimization Practice of redis in vivo push platform
- Research Report of exoskeleton robot industry - market status analysis and development prospect prediction
- Object.keys()的用法
- Why do you say that the maximum single table of MySQL database is 20million? Based on what?
- China's plastic processing machinery market trend report, technological innovation and market forecast
- Statistical learning: logistic regression and cross entropy loss (pytoch Implementation)
- 照明行业S2B2B解决方案:高效赋能产业供应链,提升企业经济效益
- Opencv learning -- arithmetic operation of image of basic operation
猜你喜欢
科普达人丨一文看懂阿里云的秘密武器“神龙架构”
周大福践行「百周年承诺」,真诚服务推动绿色环保
Years of training, towards Kata 3.0! Enter the safe container experience out of the box | dragon lizard Technology
Readis configuration and optimization of NoSQL (final chapter)
一图看懂ThreadLocal
Understand Alibaba cloud's secret weapon "dragon architecture" in the article "science popularization talent"
2022PMP考试基本情况详情了解
被PMP考试“折磨”出来的考试心得,值得你一览
The test experience "tortured" by the PMP test is worth your review
The winning rate against people is 84%, and deepmind AI has reached the level of human experts in army chess for the first time
随机推荐
Linear time sequencing
Accounting regulations and professional ethics [10]
Spark 中的 Rebalance 操作以及与Repartition操作的区别
ECCV 2022放榜了:1629篇论文中选,录用率不到20%
C# 实现 FFT 正反变换 和 频域滤波
Research Report on market supply and demand and strategy of China's Sodium Tetraphenylborate (cas+143-66-8) industry
从数数开始
Principle and general steps of SQL injection
跳跃表实例
Accounting regulations and professional ethics [9]
安信证券排名 网上开户安全吗
Accounting regulations and professional ethics [6]
Why do you say that the maximum single table of MySQL database is 20million? Based on what?
Principle and general steps of SQL injection
Visual studio 2019 (localdb) mssqllocaldb SQL Server 2014 database version is 852 and cannot be opened. This server supports 782
智慧物流园区供应链管理系统解决方案:数智化供应链赋能物流运输行业供应链新模式
一图看懂ThreadLocal
Redis: SDS source code analysis
C implementation defines a set of intermediate SQL statements that can be executed across libraries
Understand Alibaba cloud's secret weapon "dragon architecture" in the article "science popularization talent"