Golang通用限流库发布,内置主流框架集成支持
Golang通用限流库发布,内置主流框架集成支持 该库内置了大量不同的节流条件,其中包括:
- 漏桶算法
- 延迟阈值
- 指标监控
- 等等。
该库允许轻松地将这些条件组合成更复杂的节流管道,并提供了工具以便轻松集成到现有基础设施中。例如,gohalt 提供了将节流器绑定到 context 的方法。正如所述,该库还与许多流行的 Go 库进行了集成:gin、http、echo、iris、grpc、go-micro 等等。
1 回复
更多关于Golang通用限流库发布,内置主流框架集成支持的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
// 示例:使用gohalt进行HTTP请求限流
package main
import (
"net/http"
"time"
"github.com/1pkg/gohalt"
"github.com/1pkg/gohalt/gin"
"github.com/gin-gonic/gin"
)
func main() {
// 创建漏桶限流器:每秒10个请求,容量20
bucket := gohalt.NewLeakyBucket(10, 20)
// 创建延迟阈值限流器:响应时间超过100ms时触发
latency := gohalt.NewLatencyThreshold(100*time.Millisecond, time.Second)
// 组合限流条件
throttler := gohalt.NewThrottler(
gohalt.WithLimiter(bucket),
gohalt.WithLimiter(latency),
gohalt.WithMetrics(gohalt.NewPrometheusMetrics()),
)
// 创建Gin路由
r := gin.Default()
// 应用限流中间件
r.Use(gin.Throttle(throttler))
r.GET("/api/data", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"data": "success"})
})
r.Run(":8080")
}
// 示例:gRPC服务限流
package main
import (
"context"
"github.com/1pkg/gohalt"
"github.com/1pkg/gohalt/grpc"
"google.golang.org/grpc"
)
type server struct{}
func (s *server) GetData(ctx context.Context, req *DataRequest) (*DataResponse, error) {
return &DataResponse{Value: "data"}, nil
}
func main() {
// 创建令牌桶限流器
throttler := gohalt.NewThrottler(
gohalt.WithLimiter(gohalt.NewTokenBucket(100, 10)),
)
// 创建gRPC服务器并添加限流拦截器
s := grpc.NewServer(
grpc.UnaryInterceptor(grpc.ThrottleUnary(throttler)),
grpc.StreamInterceptor(grpc.ThrottleStream(throttler)),
)
// 注册服务并启动
// ...
}
// 示例:使用context进行细粒度控制
package main
import (
"context"
"fmt"
"time"
"github.com/1pkg/gohalt"
)
func processRequest(ctx context.Context) error {
// 创建请求特定的限流器
throttler := gohalt.NewThrottler(
gohalt.WithLimiter(gohalt.NewRateLimiter(5, time.Second)),
)
// 将限流器绑定到context
ctx = gohalt.WithThrottler(ctx, throttler)
// 执行需要限流的操作
if err := throttler.Do(ctx, func() error {
// 业务逻辑
fmt.Println("Processing request")
return nil
}); err != nil {
return fmt.Errorf("request throttled: %w", err)
}
return nil
}
// 示例:自定义指标监控
package main
import (
"github.com/1pkg/gohalt"
"github.com/prometheus/client_golang/prometheus"
)
func main() {
// 创建自定义Prometheus指标
requestsCounter := prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "throttled_requests_total",
Help: "Total number of throttled requests",
},
[]string{"endpoint", "status"},
)
// 注册指标
prometheus.MustRegister(requestsCounter)
// 创建带监控的限流器
throttler := gohalt.NewThrottler(
gohalt.WithLimiter(gohalt.NewLeakyBucket(50, 100)),
gohalt.WithMetrics(gohalt.NewCustomMetrics(
func(endpoint, status string) {
requestsCounter.WithLabelValues(endpoint, status).Inc()
},
)),
)
// 使用限流器...
}
gohalt库通过统一的API接口提供了灵活的限流策略组合能力,支持多种主流框架的无缝集成。漏桶算法和令牌桶算法实现符合分布式系统限流的最佳实践,延迟阈值监控能够有效防止系统雪崩。指标监控模块的抽象设计允许用户轻松对接不同的监控系统。

