Help us shape the future of Go! Take the 2026 Go Developer Survey

endpoint

package module
v0.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 22 Imported by: 0

README

nns-endpoint

NNS 端点工厂——per-service 熔断(4xx 不计失败)、HTTP 换实例重试、gRPC 连接池、弹性指标

项目主页:https://oekit.github.io/ · 名称由来:Open Easy Kit(开源 · 易用 · 工具集合) 🤖 AI Agent:本仓规范与硬规则见 AGENTS.md;机器可读索引见 llms.txt(接口签名以源码为准)。

本仓库是 ekit 拆分矩阵的成员(Round-4 微库化)。

安装

go get github.com/oekit/nns-endpoint@v0.1.3

能做什么

  • HTTP 端点:服务发现 + per-service 熔断 + 失败换实例重试,调用即函数
  • gRPC 端点:连接池 + 同款熔断语义
  • 熔断口径:4xx 不计失败(调用方错误与对端健康无关),5xx/网络错误计失败
  • 弹性指标:WithMetrics 一行接入
  • ErrCircuitOpen 可判定(与 httpx 同一 sentinel)

使用示例

HTTP 端点:调用即函数
import endpoint "github.com/oekit/nns-endpoint"

f := endpoint.NewHTTPEndpointFactory(nnsc.ServiceClient(),
    endpoint.WithMetrics(metrics.Registry, "nns"))
ep, _ := f.MakeEndpoint("payment-svc")
resp, err := ep(ctx, endpoint.HTTPRequest{ /* Method/Path/Body */ })
gRPC 端点(连接池)
gf := endpoint.NewGRPCEndpointFactory(nnsc.ServiceClient())
gep, _ := gf.MakeEndpoint("user-rpc")
resp, err := gep(ctx, endpoint.GRPCRequest{ /* ... */ })

> ⚠️ **熔断口径**:4xx 不计熔断失败;`ResetBalancer(serviceName)` 可手动重置负载均衡状态。
## 包清单

- 根包 `endpoint` — HTTPEndpointFactory/GRPCEndpointFactory,经 `nns.ServiceClient()` 构造(Round-4 自 ekit-nns 分家)

依赖:[ekit-nns](https://github.com/oekit/nns)(ServiceClient)、[ekit-httpx](https://github.com/oekit/httpx)、[ekit-metrics](https://github.com/oekit/metrics)、[ekit-logx](https://github.com/oekit/logx)、[ekit-registry](https://github.com/oekit/registry)、[ekit-concurrency](https://github.com/oekit/concurrency)。

原 `nns.MakeHTTPEndpoint/MakeGRPCEndpoint` 门面 API 随本仓迁移:改用 `endpoint.NewHTTPEndpointFactory(nnsClient.ServiceClient())`。

## License

见 [LICENSE](LICENSE)

## 矩阵总览(23 活跃模块,自动生成)

| 模块 | 内容 | 矩阵内依赖 |
|---|---|---|
| [pkg](https://github.com/oekit/pkg) | 微工具集 16 合 1(errors/validator/stringx/slicex/enumx/convert/encoding/jsonrepair/httpjson/mathx/pathx/pagination/ptrx/timex/uidgen/cache) | — |
| [concurrency](https://github.com/oekit/concurrency) | 并发与流控原语(async/group/singleflight/progress/syncx/ratelimit/retry) | — |
| [logx](https://github.com/oekit/logx) | 统一日志门面(多后端可替换 + Sink + caller 归属)+ 优雅关停 | — |
| [core](https://github.com/oekit/core) | 应用基建件(governance 治理 schema / lifecycle 契约 / network IP 工具 / version) | — |
| [istio](https://github.com/oekit/istio) | Istio Proxyless——Kitex xDS 动态熔断 | — |
| [metrics](https://github.com/oekit/metrics) | Prometheus 门面 + 弹性指标族 | [core](https://github.com/oekit/core) |
| [tracing](https://github.com/oekit/tracing) | OpenTelemetry 追踪 + trace_id 真相源 | [logx](https://github.com/oekit/logx) |
| [registry](https://github.com/oekit/registry) | 注册发现核心 + Nacos 实现 + 配置加载 + sdbridge | [core](https://github.com/oekit/core)、[logx](https://github.com/oekit/logx) |
| [data](https://github.com/oekit/data) | 缓存检查器(TTL/failTTL/inflight 合并)+ LocalCache | [concurrency](https://github.com/oekit/concurrency)、[logx](https://github.com/oekit/logx) |
| [gorm](https://github.com/oekit/gorm) | SQL/GORM 全家——连接池增强、框架无关 CRUD Service、仓储 | [logx](https://github.com/oekit/logx)、[pkg](https://github.com/oekit/pkg) |
| [redis](https://github.com/oekit/redis) | Redis 全家——客户端封装、缓存后端、分布式锁 | [concurrency](https://github.com/oekit/concurrency)、[data](https://github.com/oekit/data)、[logx](https://github.com/oekit/logx) |
| [httpx](https://github.com/oekit/httpx) | HTTP 客户端 + 负载均衡——服务发现/熔断/重试/指标/OTel 透传 | [concurrency](https://github.com/oekit/concurrency)、[core](https://github.com/oekit/core)、[logx](https://github.com/oekit/logx)、[metrics](https://github.com/oekit/metrics)、[registry](https://github.com/oekit/registry)、[tracing](https://github.com/oekit/tracing) |
| [network](https://github.com/oekit/network) | 轻量网络客户端——WebSocket/NATS/MQ 抽象、连接与流工具、Octopus 推送 | [concurrency](https://github.com/oekit/concurrency)、[logx](https://github.com/oekit/logx)、[tracing](https://github.com/oekit/tracing) |
| [timertask](https://github.com/oekit/timertask) | 分片定时任务(FNV-1a、心跳续约) | [concurrency](https://github.com/oekit/concurrency)、[logx](https://github.com/oekit/logx) |
| [middleware](https://github.com/oekit/middleware) | Hertz 自研标准中间件栈 + contrib 桥接 + hmw | [concurrency](https://github.com/oekit/concurrency)、[core](https://github.com/oekit/core)、[logx](https://github.com/oekit/logx)、[metrics](https://github.com/oekit/metrics)、[pkg](https://github.com/oekit/pkg)、[registry](https://github.com/oekit/registry)、[tracing](https://github.com/oekit/tracing) |
| [nns](https://github.com/oekit/nns) | NNS 服务治理客户端——provider 无关发现/配置/实例缓存 | [concurrency](https://github.com/oekit/concurrency)、[core](https://github.com/oekit/core)、[logx](https://github.com/oekit/logx)、[registry](https://github.com/oekit/registry) |
| [nns-endpoint](https://github.com/oekit/nns-endpoint) | NNS 端点工厂——per-service 熔断、换实例重试、gRPC 池 | [concurrency](https://github.com/oekit/concurrency)、[core](https://github.com/oekit/core)、[httpx](https://github.com/oekit/httpx)、[logx](https://github.com/oekit/logx)、[metrics](https://github.com/oekit/metrics)、[nns](https://github.com/oekit/nns)、[registry](https://github.com/oekit/registry) |
| [bootstrap](https://github.com/oekit/bootstrap) | 应用生命周期引导——bootstrap.Run 骨架 + healthz | [concurrency](https://github.com/oekit/concurrency)、[logx](https://github.com/oekit/logx) |
| [handler](https://github.com/oekit/handler) | HTTP handler 层——通用 CRUD Handler、参数绑定、版本端点 | [concurrency](https://github.com/oekit/concurrency)、[core](https://github.com/oekit/core)、[gorm](https://github.com/oekit/gorm)、[logx](https://github.com/oekit/logx)、[metrics](https://github.com/oekit/metrics)、[middleware](https://github.com/oekit/middleware)、[pkg](https://github.com/oekit/pkg)、[registry](https://github.com/oekit/registry)、[tracing](https://github.com/oekit/tracing) |
| [hertz](https://github.com/oekit/hertz) | Hertz 运行时集成——日志桥接、生命周期、SSE/health/metrics、适配器、OTel | [bootstrap](https://github.com/oekit/bootstrap)、[concurrency](https://github.com/oekit/concurrency)、[core](https://github.com/oekit/core)、[logx](https://github.com/oekit/logx)、[metrics](https://github.com/oekit/metrics)、[nns](https://github.com/oekit/nns)、[registry](https://github.com/oekit/registry)、[tracing](https://github.com/oekit/tracing) |
| [kitex](https://github.com/oekit/kitex) | Kitex 生态——日志桥接、治理热更、生命周期、BizError 桥接、kitexotel | [bootstrap](https://github.com/oekit/bootstrap)、[concurrency](https://github.com/oekit/concurrency)、[core](https://github.com/oekit/core)、[logx](https://github.com/oekit/logx)、[metrics](https://github.com/oekit/metrics)、[nns](https://github.com/oekit/nns)、[pkg](https://github.com/oekit/pkg)、[registry](https://github.com/oekit/registry) |
| [workflow](https://github.com/oekit/workflow) | 组合式流程编排——串行/并行/异步/条件分支 + Hook AOP | [concurrency](https://github.com/oekit/concurrency)、[logx](https://github.com/oekit/logx) |
| [kitex-examples](https://github.com/oekit/kitex-examples) | Kitex echo 示例——client/server + IDL + 治理配置 | [bootstrap](https://github.com/oekit/bootstrap)、[concurrency](https://github.com/oekit/concurrency)、[core](https://github.com/oekit/core)、[kitex](https://github.com/oekit/kitex)、[logx](https://github.com/oekit/logx)、[metrics](https://github.com/oekit/metrics)、[nns](https://github.com/oekit/nns)、[pkg](https://github.com/oekit/pkg)、[registry](https://github.com/oekit/registry)、[tracing](https://github.com/oekit/tracing) |

Documentation

Overview

Package endpoint 定义了统一的服务调用端点抽象,封装负载均衡、熔断和连接池等基础设施。

核心类型 Endpoint 是一个函数签名,接收 context 和请求并返回响应,使上层逻辑与具体协议解耦。 HTTPEndpointFactory 和 GRPCEndpointFactory 分别为 HTTP 和 gRPC 协议创建 Endpoint, 内部集成负载均衡选择实例、gRPC 连接池复用连接、以及基于 gobreaker 的断路器保护。

Index

Constants

This section is empty.

Variables

View Source
var ErrCircuitOpen = httpx.ErrCircuitOpen

ErrCircuitOpen 表示熔断器处于打开状态、请求被拒绝。

与 httpx.ErrCircuitOpen 是同一 sentinel:endpoint 工厂与 httpx.Client 的 熔断行为共用一个可判定错误,消费方 errors.Is 任一别名均可识别, 不必同时 import 两个包。

Functions

This section is empty.

Types

type Endpoint

type Endpoint func(ctx context.Context, request any) (any, error)

Endpoint 端点函数类型,接收上下文和请求,返回响应和错误。

type EndpointFactoryOption

type EndpointFactoryOption func(*factoryConfig)

EndpointFactoryOption 是端点工厂(HTTP/gRPC)的配置函数类型。

func WithBreakerSettings

func WithBreakerSettings(tmpl gobreaker.Settings) EndpointFactoryOption

WithBreakerSettings 设置 per-service 熔断器的参数模板。

数值字段(MaxRequests/Interval/Timeout)整体取模板值——0 是 gobreaker 的合法显式语义(如 Interval 0 = 计数器跨窗口累计),不做零值回填; 函数字段(ReadyToTrip/OnStateChange/IsSuccessful)为 nil 时沿用工厂默认。

未传 IsSuccessful 时默认判定为"4xx 不计熔断失败"(调用方请求错误与 对端健康无关);显式传入则完全接管失败判定。

func WithMetrics

func WithMetrics(reg prom.Registerer, namespace string) EndpointFactoryOption

WithMetrics 启用弹性指标(熔断状态/迁移/拒绝 + 重试尝试), 形态对齐 httpx.WithMetrics。reg 为 nil 时用全局 DefaultRegisterer; namespace 为空时用 "nns_endpoint"。多个工厂共享同一 Registry + namespace 时复用已注册 collector。

type GRPCEndpointFactory

type GRPCEndpointFactory struct {
	// contains filtered or unexported fields
}

GRPCEndpointFactory gRPC 端点工厂,负责创建 gRPC 端点并管理连接池和熔断器。

balancer 与熔断器均按服务名分片:balancer 缓存避免有状态策略(轮询)因 计数器重置失效;熔断器按服务隔离,避免单个依赖故障熔断全工厂。 balancer/熔断器均在端点闭包内按调用获取(balancerCache 读锁命中,开销可忽略), 配置热更新(ResetBalancer)对已创建的端点同样生效。服务配置(超时等)在每次 调用时从内存读取,支持 WatchService 热更新。

func NewGRPCEndpointFactory

func NewGRPCEndpointFactory(c *nnsclient.ServiceClient, opts ...EndpointFactoryOption) *GRPCEndpointFactory

NewGRPCEndpointFactory 根据服务客户端创建 gRPC 端点工厂实例。 opts 定制 per-service 熔断参数(WithBreakerSettings)等行为。 注意:gRPC 端点不做换实例重试——streaming/非幂等 RPC 的重试语义 复杂(需 header/ trailers 透传配合),如需重试在业务层按方法粒度实现。

func (*GRPCEndpointFactory) Close

func (f *GRPCEndpointFactory) Close()

Close 关闭 gRPC 端点工厂持有的连接池资源。

func (*GRPCEndpointFactory) MakeEndpoint

func (f *GRPCEndpointFactory) MakeEndpoint(serviceName string, opts ...grpc.DialOption) (Endpoint, error)

MakeEndpoint 为指定服务创建 gRPC 端点,包含负载均衡、连接池和熔断逻辑。 balancer 与熔断器在闭包内按调用获取,ResetBalancer/配置热更对存量端点生效。

func (*GRPCEndpointFactory) ResetBalancer

func (f *GRPCEndpointFactory) ResetBalancer(serviceName string)

ResetBalancer 清除指定服务的负载均衡器缓存,下次调用时按最新配置重建。

type GRPCPool

type GRPCPool struct {
	// contains filtered or unexported fields
}

GRPCPool gRPC 连接池,复用 gRPC 客户端连接。 连接数超过 maxSize 时拒绝创建新连接。 空闲超过 idleTTL 的连接在 Get 时自动驱逐。

func NewGRPCPool

func NewGRPCPool() *GRPCPool

NewGRPCPool 创建一个新的 gRPC 连接池实例。

func NewGRPCPoolWithSize

func NewGRPCPoolWithSize(maxSize int) *GRPCPool

NewGRPCPoolWithSize 创建指定最大连接数的 gRPC 连接池。

func (*GRPCPool) Close

func (p *GRPCPool) Close()

Close 关闭连接池中的所有 gRPC 连接。

func (*GRPCPool) Get

func (p *GRPCPool) Get(ctx context.Context, addr string, opts ...grpc.DialOption) (*grpc.ClientConn, error)

Get 从连接池获取指定地址的 gRPC 连接,不存在、已关闭或空闲超时时创建新连接。

并发安全说明:读锁读取 entry 与写锁校验之间存在窗口,期间该 entry 可能被 并发驱逐(Close 后删除)或替换。因此返回前必须在写锁内校验 p.conns[addr] 仍等于该 entry,否则重试——绝不把一个可能已被 Close 的连接返回给调用方。

type GRPCRequest

type GRPCRequest struct {
	ServiceName     string
	GrpcServiceName string
	Method          string
	Request         any
	Timeout         time.Duration
}

GRPCRequest gRPC 端点请求参数。

type HTTPEndpointFactory

type HTTPEndpointFactory struct {
	// contains filtered or unexported fields
}

HTTPEndpointFactory HTTP 端点工厂,负责创建 HTTP 端点并管理 HTTP 客户端和熔断器。

func NewHTTPEndpointFactory

func NewHTTPEndpointFactory(c *nnsclient.ServiceClient, opts ...EndpointFactoryOption) *HTTPEndpointFactory

NewHTTPEndpointFactory 根据服务客户端创建 HTTP 端点工厂实例。 opts 定制 per-service 熔断参数(WithBreakerSettings)、弹性指标 (WithMetrics)等行为。

func (*HTTPEndpointFactory) Close

func (f *HTTPEndpointFactory) Close()

Close 关闭 HTTP 端点工厂持有的资源。 Hertz client 连接池无显式释放 API(随进程生命周期),httpx.Client 的 endpointManager 在本工厂场景未启用,故此处无资源可释放; 保留方法以满足工厂统一 Close 契约。

func (*HTTPEndpointFactory) MakeEndpoint

func (f *HTTPEndpointFactory) MakeEndpoint(serviceName string) (Endpoint, error)

MakeEndpoint 为指定服务创建 HTTP 端点。

重试语义(消费服务配置 ServiceBasic.Retry,Nacos 配置缺省 3): 失败时换实例重试,最多额外 Retry 次尝试;5xx 与网络错误重试, 4xx 不重试(确定性请求错误)。熔断 Execute 包住整组尝试—— 一次调用计一次熔断样本(与 httpx.WithCircuitBreaker + WithRetryConfig 的层次结构一致),避免单次调用的多次尝试 撑爆连续失败计数。每次尝试独立 per-attempt 超时,最坏总耗时 为 (1+Retry) × ReadTimeout。

func (*HTTPEndpointFactory) ResetBalancer

func (f *HTTPEndpointFactory) ResetBalancer(serviceName string)

ResetBalancer 清除指定服务的负载均衡器缓存。

type HTTPRequest

type HTTPRequest struct {
	Method  string
	Path    string
	Body    any
	Header  map[string]string
	Query   map[string]string
	Result  any
	Timeout time.Duration
}

HTTPRequest HTTP 端点请求参数。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL