golang微服务框架插件Microservice的创建与使用
Golang 微服务框架插件 Microservice 的创建与使用
安装
git clone ginhub.com/claygod/microservice
cd microservice
make build
make run
完成后在浏览器访问 localhost:8080
版本检查
git clone ginhub.com/claygod/microservice
cd microservice
make build
make version
或
git clone ginhub.com/claygod/microservice
cd microservice
make build
micro --version
端点
代码位于 /services/gateways/gatein/gatein.go
/
- 欢迎处理器/healthz/ready
- 用于 SRE/healthz
- 用于 Kubernetes/readyness
- 用于 Kubernetes/metrics
- Prometheus 指标/swagger
- 生成 API 的 Swagger 文档/public/v1/bar/:key
- 公共路由(示例)
注意:来自外部负载均衡器的请求应该转发到 /public
而不是端点根路径。这样服务路由中的指标和其他私有信息对外部用户将不可访问。
使用
构建并运行 main.go
示例请求:
localhost:8080/public/v1/bar/one
->{"Data":"three"}
localhost:8080/public/v1/bar/secret
-> 响应 404localhost:8080/public/v1/bar/looooonnngggoooooggkkkeeyyyyyyy
-> 响应 400 (无效)localhost:8080/healthz/ready
-> 前5分钟 - 503 之后 200 (示例)localhost:8080/healthz
-> 前5分钟 - 503 之后 200 (示例)localhost:8080/readyness
-> 响应 200localhost:8080/swagger
-> json-swagger
Swagger
应用程序启动后,第一次调用 /swagger
路由时,会重新生成 config/swagger.yaml
文件。
环境
在环境变量中添加 export GATE_IN_TITLE=Yo-ho-ho!
👍
然后在浏览器打开 http://localhost:8080/
🎉
清洁架构
重要:按层分配架构实体
实体
路径 /domain
用例
路径 /usecases
接口
路径 /service
基础设施
路径 /app
、/config
和核心
配置
默认配置文件:
config/config.yaml
在命令行指定其他文件:
yourservice -config other.yaml
依赖
github.com/claygod/tools v0.1.2
github.com/dsbasko/go-cfg v1.2.0
github.com/go-playground/validator/v10 v10.22.1
github.com/google/uuid v1.3.0
github.com/julienschmidt/httprouter v1.3.0
github.com/pborman/getopt v1.1.0
github.com/prometheus/client_golang v1.11.1
github.com/savaki/swag v0.0.0-20170722173931-3a75479e44a3
sigs.k8s.io/yaml v1.4.0
github.com/BurntSushi/toml v1.3.2 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/caarlos0/env/v10 v10.0.0 // indirect
github.com/cespare/xxhash/v2 v2.1.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/golang/protobuf v1.5.0 // indirect
github.com/joho/godotenv v1.5.1 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/prometheus/client_model v0.2.0 // indirect
github.com/prometheus/common v0.26.0 // indirect
github.com/prometheus/procfs v0.6.0 // indirect
github.com/spf13/pflag v1.极好的代码示例!以下是一个完整的 Golang 微服务示例,使用 Microservice 框架:
```go
package main
import (
"github.com/claygod/microservice"
"github.com/julienschmidt/httprouter"
"net/http"
)
func main() {
// 创建新的微服务实例
ms := microservice.New()
// 添加自定义路由
router := httprouter.New()
// 自定义欢迎路由
router.GET("/", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
w.Write([]byte("Welcome to Microservice Demo!"))
})
// 示例API路由
router.GET("/api/v1/hello/:name", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
name := ps.ByName("name")
w.Write([]byte("Hello " + name + "!"))
})
// 将自定义路由器添加到微服务
ms.SetRouter(router)
// 启动服务
if err := ms.Run(); err != nil {
panic(err)
}
}
结论
Microservice 并不声称自己是唯一正确的解决方案,但在某些情况下,它可以帮助你创建自己的微服务架构,成为未来应用程序的原型。
给我们一颗星!
提示:如果你喜欢或正在使用这个项目来学习或启动你的解决方案,请给它一颗星。谢谢!
许可证
GNU GENERAL PUBLIC LICENSE Version 3
版权
Copyright © 2017-2025 Eduard Sesigin. 保留所有权利。联系方式: claygod@yandex.ru
更多关于golang微服务框架插件Microservice的创建与使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html
更多关于golang微服务框架插件Microservice的创建与使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
Golang微服务框架插件Microservice的创建与使用
Micro是一个轻量级的Go微服务框架,它提供了一系列工具和插件来简化微服务开发。下面我将介绍如何使用Micro框架创建和使用微服务插件。
1. 安装Micro
首先需要安装Micro框架:
go get github.com/micro/micro/v3
2. 创建基础微服务
创建一个简单的微服务:
package main
import (
"context"
"fmt"
"log"
"github.com/micro/micro/v3/service"
"github.com/micro/micro/v3/service/logger"
)
type Greeter struct{}
func (g *Greeter) Hello(ctx context.Context, req *string, rsp *string) error {
*rsp = fmt.Sprintf("Hello, %s!", *req)
return nil
}
func main() {
// 创建新服务
srv := service.New(
service.Name("greeter"),
)
// 注册处理器
srv.Handle(srv.Server().NewHandler(&Greeter{}))
// 运行服务
if err := srv.Run(); err != nil {
logger.Fatal(err)
}
}
3. 创建自定义插件
Micro允许你创建自定义插件来扩展功能。下面是一个日志插件的示例:
package logger
import (
"context"
"log"
"github.com/micro/micro/v3/service/server"
)
type LogWrapper struct {
server.Handler
}
func (l *LogWrapper) Process(ctx context.Context, req server.Request, rsp interface{}) error {
log.Printf("Before call: %s", req.Endpoint())
err := l.Handler.Process(ctx, req, rsp)
log.Printf("After call: %s", req.Endpoint())
return err
}
func NewLogWrapper(fn server.HandlerFunc) server.Handler {
return &LogWrapper{fn}
}
// 注册为全局插件
func init() {
server.RegisterHandlerWrapper(NewLogWrapper)
}
4. 使用内置插件
Micro提供了许多内置插件,比如:
使用Broker插件(消息队列)
package main
import (
"context"
"fmt"
"time"
"github.com/micro/micro/v3/service"
"github.com/micro/micro/v3/service/broker"
)
func main() {
// 创建服务
srv := service.New()
// 订阅主题
_, err := broker.Subscribe("example.topic", func(p broker.Event) error {
fmt.Printf("Received message: %s\n", string(p.Message().Body))
return nil
})
if err != nil {
fmt.Println(err)
return
}
// 发布消息
go func() {
for i := 0; i < 5; i++ {
broker.Publish("example.topic", &broker.Message{
Body: []byte(fmt.Sprintf("Message %d", i)),
})
time.Sleep(1 * time.Second)
}
}()
// 运行服务
if err := srv.Run(); err != nil {
fmt.Println(err)
}
}
使用Registry插件(服务发现)
package main
import (
"fmt"
"time"
"github.com/micro/micro/v3/service"
"github.com/micro/micro/v3/service/registry"
)
func main() {
// 创建服务
srv := service.New()
// 列出所有服务
go func() {
for {
services, err := registry.ListServices()
if err != nil {
fmt.Println(err)
continue
}
for _, service := range services {
fmt.Printf("Service: %s\n", service.Name)
}
time.Sleep(5 * time.Second)
}
}()
// 运行服务
if err := srv.Run(); err != nil {
fmt.Println(err)
}
}
5. 插件配置
Micro支持通过配置文件或环境变量配置插件:
package main
import (
"github.com/micro/micro/v3/service"
"github.com/micro/micro/v3/service/config"
)
type Config struct {
Host string `json:"host"`
Port int `json:"port"`
}
func main() {
// 创建服务
srv := service.New()
// 加载配置
var cfg Config
if err := config.Get("myconfig").Scan(&cfg); err != nil {
srv.Log().Fatalf("Error loading config: %v", err)
}
srv.Log().Infof("Config: %+v", cfg)
// 运行服务
if err := srv.Run(); err != nil {
srv.Log().Fatal(err)
}
}
6. 中间件插件
创建HTTP中间件插件:
package middleware
import (
"net/http"
"github.com/micro/micro/v3/service/web"
)
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 验证逻辑
if r.Header.Get("Authorization") == "" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// 调用下一个处理器
next.ServeHTTP(w, r)
})
}
// 注册中间件
func init() {
web.RegisterMiddleware(AuthMiddleware)
}
7. 最佳实践
-
插件设计原则:
- 保持插件单一职责
- 提供清晰的接口
- 支持可配置性
-
性能考虑:
- 避免插件中的阻塞操作
- 使用缓存优化重复计算
- 考虑插件的执行顺序
-
错误处理:
- 提供有意义的错误信息
- 允许插件错误不影响主流程(可配置)
Micro框架的插件系统非常灵活,你可以根据需要创建各种类型的插件来扩展微服务功能。通过合理使用插件,可以大大提高微服务的可维护性和可扩展性。