当前位置:网站首页>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
边栏推荐
- 基于check-point实现图数据构建任务
- China's plastic processing machinery market trend report, technological innovation and market forecast
- DIY a low-cost multi-functional dot matrix clock!
- Accounting regulations and professional ethics [10]
- Research Report on market supply and demand and strategy of China's four sided flat bag industry
- Embedded software architecture design - function call
- Accounting regulations and professional ethics [11]
- 对人胜率84%,DeepMind AI首次在西洋陆军棋中达到人类专家水平
- Task state rollback and data blocking tasks based on check point mechanism
- Detailed process of DC-2 range construction and penetration practice (DC range Series)
猜你喜欢
随机推荐
Research Report of exoskeleton robot industry - market status analysis and development prospect prediction
Is it safe for Anxin securities to open an account online? Is the account opening fee charged
[Chongqing Guangdong education] National Open University spring 2019 1248 public sector human resource management reference questions
《吐血整理》保姆级系列教程-玩转Fiddler抓包教程(2)-初识Fiddler让你理性认识一下
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
多年锤炼,迈向Kata 3.0 !走进开箱即用的安全容器体验之旅| 龙蜥技术
Visual Studio 2019 (LocalDB)MSSQLLocalDB SQL Server 2014 数据库版本为852无法打开,此服务器支持782
基于check-point实现图数据构建任务
周大福践行「百周年承诺」,真诚服务推动绿色环保
Median and order statistics
Array filter fliter in JS
Use and principle of thread pool
C implementation defines a set of intermediate SQL statements that can be executed across libraries
实战:fabric 用户证书吊销操作流程
Accounting regulations and professional ethics [11]
System. Currenttimemillis() and system Nanotime (), which is faster? Don't use it wrong!
PyTorch深度学习快速入门教程
Software Engineer vs Hardware Engineer
Embedded software architecture design - function call
表单传递时,如何隐式将值传过去