config

package
v1.1.21 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2025 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AppConfig = &Config{
	Application: ApplicationConfig,
	Logger:      LoggerConfig,
	HTTP:        HttpConfig,
	GRPC:        GrpcConfig,
	Etcd:        EtcdConfig,
	JWT:         JwtConfig,
	Database:    DatabaseConfig,
	Cache:       CacheConfig,
	Queue:       QueueConfig,
	Locker:      LockerConfig,
	EventBus:    nil,
	Tenants:     TenantsConfig,
}
View Source
var ApplicationConfig = new(Application)
View Source
var CacheConfig = new(Cache)
View Source
var (
	DatabaseConfig = new(Database)
)
View Source
var EtcdConfig = new(ETCDConfig)
View Source
var GrpcConfig = new(GRPCConfig)
View Source
var HttpConfig = new(HTTPConfig)
View Source
var JwtConfig = new(JWTConfig)
View Source
var LockerConfig = new(Locker)
View Source
var LoggerConfig = new(Logger)
View Source
var QueueConfig = new(Queue)
View Source
var ServiceConfigMap = make(map[string]ServiceConfig)
View Source
var SslConfig = new(SSL)
View Source
var TenantsConfig = new(Tenants)

Functions

func GetRedisClient

func GetRedisClient() *redis.Client

GetRedisClient 获取redis客户端

func SetRedisClient

func SetRedisClient(c *redis.Client)

SetRedisClient 设置redis客户端

func Setup

func Setup(configYml string) error

Types

type Application

type Application struct {
	Mode     string `mapstructure:"mode" json:"mode"`         // 环境: dev, test, prod
	Name     string `mapstructure:"name" json:"name"`         // 应用名称
	EnableDP bool   `mapstructure:"enabledp" json:"enabledp"` // 数据权限功能开关

}

Application 应用程序配置

type BacklogDetectionConfig added in v1.1.19

type BacklogDetectionConfig struct {
	Enabled          bool          `mapstructure:"enabled"`
	MaxLagThreshold  int64         `mapstructure:"maxLagThreshold"`
	MaxTimeThreshold time.Duration `mapstructure:"maxTimeThreshold"`
	CheckInterval    time.Duration `mapstructure:"checkInterval"`
}

BacklogDetectionConfig 通用积压检测配置(向后兼容)

type Cache

type Cache struct {
	Redis  *RedisConnectOptions
	Memory interface{}
}

func (Cache) Setup

func (e Cache) Setup() (storage.AdapterCache, error)

Setup 构造cache 顺序 redis > 其他 > memory

type ClientMiddlewaresConfig added in v1.1.18

type ClientMiddlewaresConfig struct {
	Trace      bool `mapstructure:"trace" json:"trace,default=true"`           // 链路跟踪
	Duration   bool `mapstructure:"duration" json:"duration,default=true"`     // 持续时间统计
	Prometheus bool `mapstructure:"prometheus" json:"prometheus,default=true"` // Prometheus监控
	Breaker    bool `mapstructure:"breaker" json:"breaker,default=true"`       // 熔断器
}

ClientMiddlewaresConfig 客户端中间件配置

type Config

type Config struct {
	Application *Application    `mapstructure:"application"`
	HTTP        *HTTPConfig     `mapstructure:"http" json:"http"`
	GRPC        *GRPCConfig     `mapstructure:"grpc" json:"grpc"`
	Etcd        *ETCDConfig     `mapstructure:"etcd" json:"etcd"`
	Logger      *Logger         `mapstructure:"logger"`
	SSL         *SSL            `mapstructure:"ssl"`
	JWT         *JWTConfig      `mapstructure:"jwt"`
	Database    *Database       `mapstructure:"database"`
	Cache       *Cache          `mapstructure:"cache"`
	Queue       *Queue          `mapstructure:"queue"`
	EventBus    *EventBusConfig `mapstructure:"eventBus"`
	Locker      *Locker         `mapstructure:"locker"`
	Tenants     *Tenants        `mapstructure:"tenants"`
}

Config 顶层配置结构

type ConsumerConfig added in v1.1.19

type ConsumerConfig struct {
	GroupID           string        `mapstructure:"groupId"`           // 消费者组ID
	AutoOffsetReset   string        `mapstructure:"autoOffsetReset"`   // 偏移量重置策略 (earliest, latest, none)
	SessionTimeout    time.Duration `mapstructure:"sessionTimeout"`    // 会话超时时间
	HeartbeatInterval time.Duration `mapstructure:"heartbeatInterval"` // 心跳间隔

}

ConsumerConfig 消费者配置 - 用户配置层(简化) 只包含用户需要关心的核心配置字段

type DBConfig added in v1.1.6

type DBConfig struct {
	Driver          string     `mapstructure:"driver"`
	Source          string     `mapstructure:"source"`
	ConnMaxIdleTime int        `mapstructure:"connmaxidletime"`
	ConnMaxLifeTime int        `mapstructure:"connmaxlifetime"`
	MaxIdleConns    int        `mapstructure:"maxidleconns"`
	MaxOpenConns    int        `mapstructure:"maxopenconns"`
	Registers       []Register `mapstructure:"registers"`
}

DBConfig 数据库具体配置

type Database

type Database struct {
	MasterDB  DBConfig `mapstructure:"masterDB"`
	CommandDB DBConfig `mapstructure:"commandDB"`
	QueryDB   DBConfig `mapstructure:"queryDB"`
}

Database 数据库配置

type DatabaseDefaults added in v1.1.11

type DatabaseDefaults struct {
	Driver       string `mapstructure:"driver"`
	MaxOpenConns int    `mapstructure:"maxOpenConns"`
	MaxIdleConns int    `mapstructure:"maxIdleConns"`
}

type DefaultConfig added in v1.1.11

type DefaultConfig struct {
	Database DatabaseDefaults `mapstructure:"database"`
}

type ETCDConfig added in v1.1.18

type ETCDConfig struct {
	Enabled     bool      `mapstructure:"enabled" json:"enabled"`         // 是否启用ETCD
	Hosts       []string  `mapstructure:"hosts" json:"hosts"`             // ETCD主机列表
	Username    string    `mapstructure:"username" json:"username"`       // 用户名
	Password    string    `mapstructure:"password" json:"password"`       // 密码
	Namespace   string    `mapstructure:"namespace" json:"namespace"`     // 命名空间前缀
	DialTimeout int       `mapstructure:"dialTimeout" json:"dialTimeout"` // 连接超时(秒)
	Timeout     int       `mapstructure:"timeout" json:"timeout"`         // 操作超时(秒)
	TLS         TLSConfig `mapstructure:"tls" json:"tls"`                 // TLS配置
}

ETCDConfig ETCD配置

func (*ETCDConfig) GetNamespacedKey added in v1.1.18

func (e *ETCDConfig) GetNamespacedKey(key string) string

GetNamespacedKey 获取带命名空间的键名

func (*ETCDConfig) IsEnabled added in v1.1.18

func (e *ETCDConfig) IsEnabled() bool

IsEnabled 检查etcd是否启用

type ErrorHandlingConfig added in v1.1.19

type ErrorHandlingConfig struct {
	DeadLetterTopic  string        `mapstructure:"deadLetterTopic"`
	MaxRetryAttempts int           `mapstructure:"maxRetryAttempts"`
	RetryBackoffBase time.Duration `mapstructure:"retryBackoffBase"`
	RetryBackoffMax  time.Duration `mapstructure:"retryBackoffMax"`
}

ErrorHandlingConfig 错误处理配置

type EventBusConfig added in v1.1.3

type EventBusConfig struct {
	// 基础配置
	Type        string `mapstructure:"type"`        // kafka, nats, memory
	ServiceName string `mapstructure:"serviceName"` // 微服务名称

	// 统一特性配置(适用于所有EventBus类型)
	HealthCheck HealthCheckConfig `mapstructure:"healthCheck"` // 健康检查
	Monitoring  MetricsConfig     `mapstructure:"monitoring"`  // 监控(复用现有的MetricsConfig)
	Security    SecurityConfig    `mapstructure:"security"`    // 安全

	// 发布端配置
	Publisher PublisherConfig `mapstructure:"publisher"`

	// 订阅端配置
	Subscriber SubscriberConfig `mapstructure:"subscriber"`

	// 具体实现配置
	Kafka  KafkaConfig  `mapstructure:"kafka"`  // Kafka配置
	NATS   NATSConfig   `mapstructure:"nats"`   // NATS配置
	Memory MemoryConfig `mapstructure:"memory"` // Memory配置
}

EventBusConfig 事件总线配置

func (*EventBusConfig) SetDefaults added in v1.1.19

func (c *EventBusConfig) SetDefaults()

SetDefaults 为EventBusConfig设置默认值

func (*EventBusConfig) Validate added in v1.1.19

func (c *EventBusConfig) Validate() error

Validate 验证EventBusConfig配置

type GRPCClientConfig added in v1.1.18

type GRPCClientConfig struct {
	Enabled       bool          `mapstructure:"enabled" json:"enabled,default=true"`            // 是否启用gRPC客户端
	ServiceKey    string        `mapstructure:"serviceKey" json:"serviceKey"`                   // 服务发现键名
	Timeout       int64         `mapstructure:"timeout" json:"timeout,default=2000"`            // 超时时间(毫秒)
	KeepaliveTime time.Duration `mapstructure:"keepaliveTime" json:"keepaliveTime,default=20s"` // Keepalive时间

	// 连接配置
	Endpoints    []string `mapstructure:"endpoints" json:"endpoints,optional"`           // 直连端点列表
	Target       string   `mapstructure:"target" json:"target,optional"`                 // gRPC目标地址
	NonBlock     bool     `mapstructure:"nonBlock" json:"nonBlock,optional"`             // 非阻塞模式
	UseDiscovery bool     `mapstructure:"useDiscovery" json:"useDiscovery,default=true"` // 是否使用服务发现

	// 认证配置
	App   string `mapstructure:"app" json:"app,optional"`     // 应用名称
	Token string `mapstructure:"token" json:"token,optional"` // 认证Token

	// 性能配置
	Retries        int `mapstructure:"retries" json:"retries,default=3"`              // 重试次数
	MaxRecvMsgSize int `mapstructure:"maxRecvMsgSize" json:"maxRecvMsgSize,optional"` // 最大接收消息大小
	MaxSendMsgSize int `mapstructure:"maxSendMsgSize" json:"maxSendMsgSize,optional"` // 最大发送消息大小

	// 中间件配置
	Middlewares ClientMiddlewaresConfig `mapstructure:"middlewares" json:"middlewares,optional"` // 中间件配置
}

GRPCClientConfig gRPC客户端配置

func (*GRPCClientConfig) ToGoZeroRpcClientConf added in v1.1.18

func (c *GRPCClientConfig) ToGoZeroRpcClientConf(etcdConfig *ETCDConfig) map[string]interface{}

ToGoZeroRpcClientConf 转换为go-zero的RpcClientConf

type GRPCConfig added in v1.1.18

type GRPCConfig struct {
	Server GRPCServerConfig `mapstructure:"server" json:"server"` // gRPC服务配置
	Client GRPCClientConfig `mapstructure:"client" json:"client"` // gRPC客户端配置
}

GRPCConfig gRPC服务配置

type GRPCServerConfig added in v1.1.18

type GRPCServerConfig struct {
	Enabled    bool   `mapstructure:"enabled" json:"enabled,default=true"`    // 是否启用gRPC服务
	ListenOn   string `mapstructure:"listenOn" json:"listenOn,default=:9000"` // 监听地址
	ServiceKey string `mapstructure:"serviceKey" json:"serviceKey"`           // 服务发现键名
	Timeout    int64  `mapstructure:"timeout" json:"timeout,default=2000"`    // 超时时间(毫秒)

	// 认证配置
	Auth bool `mapstructure:"auth" json:"auth,optional"` // 是否启用认证

	// 性能控制
	CpuThreshold   int64 `mapstructure:"cpuThreshold" json:"cpuThreshold,default=900,range=[0:1000]"` // CPU阈值
	StrictControl  bool  `mapstructure:"strictControl" json:"strictControl,optional"`                 // 严格控制模式
	MaxRecvMsgSize int   `mapstructure:"maxRecvMsgSize" json:"maxRecvMsgSize,optional"`               // 最大接收消息大小
	MaxSendMsgSize int   `mapstructure:"maxSendMsgSize" json:"maxSendMsgSize,optional"`               // 最大发送消息大小

	// TLS配置
	TLS TLSConfig `mapstructure:"tls" json:"tls,optional"` // TLS配置

	// KeepAlive配置
	KeepAlive KeepAliveConfig `mapstructure:"keepAlive" json:"keepAlive,optional"` // 保活配置

	// 中间件配置
	Middlewares ServerMiddlewaresConfig `mapstructure:"middlewares" json:"middlewares,optional"` // 中间件配置

	// 自定义服务配置
	Services map[string]ServiceConfig `mapstructure:"services" json:"services,optional"` // 服务配置
}

GRPCServerConfig gRPC服务端配置

func (*GRPCServerConfig) ToGoZeroRpcServerConf added in v1.1.18

func (c *GRPCServerConfig) ToGoZeroRpcServerConf(etcdConfig *ETCDConfig) map[string]interface{}

ToGoZeroRpcServerConf 转换为go-zero的RpcServerConf

type HTTPConfig added in v1.1.10

type HTTPConfig struct {
	Enabled        bool      `mapstructure:"enabled" json:"enabled"`               // 是否启用HTTP服务
	Host           string    `mapstructure:"host" json:"host"`                     // 服务器绑定IP
	Port           int       `mapstructure:"port" json:"port"`                     // HTTP端口
	ReadTimeout    int       `mapstructure:"readtimeout" json:"readtimeout"`       // 读取超时(秒)
	WriteTimeout   int       `mapstructure:"writetimeout" json:"writetimeout"`     // 写入超时(秒)
	IdleTimeout    int       `mapstructure:"idletimeout" json:"idletimeout"`       // 空闲超时(秒)
	MaxHeaderBytes int       `mapstructure:"maxheaderbytes" json:"maxheaderbytes"` // 最大请求头(MB)
	SSL            SSLConfig `mapstructure:"ssl" json:"ssl"`                       // SSL配置
}

HTTPConfig HTTP服务器配置(Gin)

type HealthCheckConfig added in v1.1.19

type HealthCheckConfig struct {
	// 基础配置
	Enabled bool `mapstructure:"enabled"` // 是否启用健康检查

	// 发布器配置
	Publisher HealthCheckPublisherConfig `mapstructure:"publisher"`

	// 订阅监控器配置
	Subscriber HealthCheckSubscriberConfig `mapstructure:"subscriber"`
}

HealthCheckConfig 统一健康检查配置

type HealthCheckPublisherConfig added in v1.1.19

type HealthCheckPublisherConfig struct {
	Topic            string        `mapstructure:"topic"`            // 健康检查发布主题(可选,默认自动生成)
	Interval         time.Duration `mapstructure:"interval"`         // 发布间隔(默认2分钟)
	Timeout          time.Duration `mapstructure:"timeout"`          // 发布超时(默认10秒)
	FailureThreshold int           `mapstructure:"failureThreshold"` // 连续失败阈值,触发重连(默认3次)
	MessageTTL       time.Duration `mapstructure:"messageTTL"`       // 消息存活时间(默认5分钟)
}

HealthCheckPublisherConfig 健康检查发布器配置

type HealthCheckSubscriberConfig added in v1.1.19

type HealthCheckSubscriberConfig struct {
	Topic             string        `mapstructure:"topic"`             // 健康检查订阅主题(可选,默认自动生成)
	MonitorInterval   time.Duration `mapstructure:"monitorInterval"`   // 监控检查间隔(默认30秒)
	WarningThreshold  int           `mapstructure:"warningThreshold"`  // 警告阈值(默认3次)
	ErrorThreshold    int           `mapstructure:"errorThreshold"`    // 错误阈值(默认5次)
	CriticalThreshold int           `mapstructure:"criticalThreshold"` // 严重阈值(默认10次)
}

HealthCheckSubscriberConfig 健康检查订阅监控器配置

type JWTConfig added in v1.1.10

type JWTConfig struct {
	Secret  string `mapstructure:"secret"`
	Timeout int    `mapstructure:"timeout"`
}

JWT JWT配置

type JetStreamConfig added in v1.1.19

type JetStreamConfig struct {
	Enabled        bool          `mapstructure:"enabled"`
	Domain         string        `mapstructure:"domain"`
	APIPrefix      string        `mapstructure:"apiPrefix"`
	PublishTimeout time.Duration `mapstructure:"publishTimeout"`
	AckWait        time.Duration `mapstructure:"ackWait"`
	MaxDeliver     int           `mapstructure:"maxDeliver"`

	// 流配置
	Stream StreamConfig `mapstructure:"stream"`

	// 消费者配置
	Consumer NATSConsumerConfig `mapstructure:"consumer"`
}

JetStreamConfig JetStream配置

type KafkaConfig added in v1.1.3

type KafkaConfig struct {
	Brokers  []string       `mapstructure:"brokers"`  // Kafka集群地址
	Producer ProducerConfig `mapstructure:"producer"` // 生产者配置
	Consumer ConsumerConfig `mapstructure:"consumer"` // 消费者配置

}

KafkaConfig Kafka配置 - 用户配置层(简化) 只包含用户需要关心的核心配置字段

type KeepAliveConfig added in v1.1.10

type KeepAliveConfig struct {
	Time                int  `mapstructure:"time" json:"time,default=7200"`                                // 保活时间(秒)
	Timeout             int  `mapstructure:"timeout" json:"timeout,default=20"`                            // 保活超时(秒)
	PermitWithoutStream bool `mapstructure:"permitWithoutStream" json:"permitWithoutStream,default=false"` // 允许无流保活
}

KeepAliveConfig gRPC KeepAlive配置

type Locker

type Locker struct {
	Redis *RedisConnectOptions `mapstructure:"redis"`
}

Locker 锁配置

func (Locker) Empty

func (e Locker) Empty() bool

Empty 空设置

func (Locker) Setup

func (e Locker) Setup() (storage.AdapterLocker, error)

Setup 启用顺序 redis > 其他 > memory

type Logger

type Logger struct {
	Type            string `mapstructure:"type"`            // zap,logrus,或自研,无用删除by jiyuanjje
	Path            string `mapstructure:"path"`            // 日志文件路径
	Level           string `mapstructure:"level"`           // 日志级别
	Stdout          bool   `mapstructure:"stdout"`          // 是否输出到标准控制台(true:输出,false:不输出)
	MaxSize         int    `mapstructure:"maxsize"`         // 每个日志文件最大多少MB,一般设置50MB add by jiyuanjje
	ErrorMaxAge     int    `mapstructure:"errormaxage"`     // error日志文件保留天数,一般设置14天 add by jiyuanjje
	InfoMaxAge      int    `mapstructure:"infomaxage"`      // info日志文件保留天数,一般设置3天 add by jiyuanjje
	MaxBackups      int    `mapstructure:"maxbackups"`      // 日志文件保留个数,一般设置20个 add by jiyuanjje
	EnabledDB       bool   `mapstructure:"enableddb"`       // 是否启用数据库日志(true:启用,false:不启用)
	GormLoggerLevel int    `mapstructure:"gormloggerlevel"` // 数据库日志打印级别(4:Info,3 Warn,2 Error,1 Silent)add by jiyuanjie
}

Logger 日志配置

type MemoryConfig added in v1.1.19

type MemoryConfig struct {
	MaxChannelSize int `mapstructure:"maxChannelSize"` // 最大通道大小
	BufferSize     int `mapstructure:"bufferSize"`     // 缓冲区大小
}

MemoryConfig Memory配置

type MetricsConfig added in v1.1.19

type MetricsConfig struct {
	Enabled         bool          `mapstructure:"enabled"`
	CollectInterval time.Duration `mapstructure:"collectInterval"`
	ExportEndpoint  string        `mapstructure:"exportEndpoint"`
}

MetricsConfig 指标配置

type NATSConfig added in v1.1.19

type NATSConfig struct {
	URLs              []string           `mapstructure:"urls"`              // NATS服务器地址
	ClientID          string             `mapstructure:"clientId"`          // 客户端ID
	MaxReconnects     int                `mapstructure:"maxReconnects"`     // 最大重连次数
	ReconnectWait     time.Duration      `mapstructure:"reconnectWait"`     // 重连等待时间
	ConnectionTimeout time.Duration      `mapstructure:"connectionTimeout"` // 连接超时
	JetStream         JetStreamConfig    `mapstructure:"jetstream"`         // JetStream配置
	Security          NATSSecurityConfig `mapstructure:"security"`          // NATS安全配置
}

NATSConfig NATS配置

type NATSConsumerConfig added in v1.1.19

type NATSConsumerConfig struct {
	DurableName   string          `mapstructure:"durableName"`
	DeliverPolicy string          `mapstructure:"deliverPolicy"` // all, last, new, by_start_sequence, by_start_time
	AckPolicy     string          `mapstructure:"ackPolicy"`     // none, all, explicit
	ReplayPolicy  string          `mapstructure:"replayPolicy"`  // instant, original
	MaxAckPending int             `mapstructure:"maxAckPending"`
	MaxWaiting    int             `mapstructure:"maxWaiting"`
	MaxDeliver    int             `mapstructure:"maxDeliver"`
	BackOff       []time.Duration `mapstructure:"backOff"`
}

NATSConsumerConfig NATS消费者配置

type NATSSecurityConfig added in v1.1.19

type NATSSecurityConfig struct {
	Enabled    bool   `mapstructure:"enabled"`
	Token      string `mapstructure:"token"`
	Username   string `mapstructure:"username"`
	Password   string `mapstructure:"password"`
	NKeyFile   string `mapstructure:"nkeyFile"`
	CredFile   string `mapstructure:"credFile"`
	CertFile   string `mapstructure:"certFile"`
	KeyFile    string `mapstructure:"keyFile"`
	CAFile     string `mapstructure:"caFile"`
	SkipVerify bool   `mapstructure:"skipVerify"`
}

NATSSecurityConfig NATS安全配置

type NSQOptions

type NSQOptions struct {
	DialTimeout time.Duration `opt:"dial_timeout" default:"1s"`

	// Deadlines for network reads and writes
	ReadTimeout  time.Duration `opt:"read_timeout" min:"100ms" max:"5m" default:"60s"`
	WriteTimeout time.Duration `opt:"write_timeout" min:"100ms" max:"5m" default:"1s"`

	// Addresses is the local address to use when dialing an nsqd.
	Addresses []string `opt:"addresses"`

	// Duration between polling lookupd for new producers, and fractional jitter to add to
	// the lookupd pool loop. this helps evenly distribute requests even if multiple consumers
	// restart at the same time
	//
	// NOTE: when not using nsqlookupd, LookupdPollInterval represents the duration of time between
	// reconnection attempts
	LookupdPollInterval time.Duration `opt:"lookupd_poll_interval" min:"10ms" max:"5m" default:"60s"`
	LookupdPollJitter   float64       `opt:"lookupd_poll_jitter" min:"0" max:"1" default:"0.3"`

	// Maximum duration when REQueueing (for doubling of deferred requeue)
	MaxRequeueDelay     time.Duration `opt:"max_requeue_delay" min:"0" max:"60m" default:"15m"`
	DefaultRequeueDelay time.Duration `opt:"default_requeue_delay" min:"0" max:"60m" default:"90s"`

	// Maximum amount of time to backoff when processing fails 0 == no backoff
	MaxBackoffDuration time.Duration `opt:"max_backoff_duration" min:"0" max:"60m" default:"2m"`
	// Unit of time for calculating consumer backoff
	BackoffMultiplier time.Duration `opt:"backoff_multiplier" min:"0" max:"60m" default:"1s"`

	// Maximum number of times this consumer will attempt to process a message before giving up
	MaxAttempts uint16 `opt:"max_attempts" min:"0" max:"65535" default:"5"`

	// Duration to wait for a message from an nsqd when in a state where RDY
	// counts are re-distributed (e.g. max_in_flight < num_producers)
	LowRdyIdleTimeout time.Duration `opt:"low_rdy_idle_timeout" min:"1s" max:"5m" default:"10s"`
	// Duration to wait until redistributing RDY for an nsqd regardless of LowRdyIdleTimeout
	LowRdyTimeout time.Duration `opt:"low_rdy_timeout" min:"1s" max:"5m" default:"30s"`
	// Duration between redistributing max-in-flight to connections
	RDYRedistributeInterval time.Duration `opt:"rdy_redistribute_interval" min:"1ms" max:"5s" default:"5s"`

	// Identifiers sent to nsqd representing this client
	// UserAgent is in the spirit of HTTP (default: "<client_library_name>/<version>")
	ClientID  string `opt:"client_id"` // (defaults: short hostname)
	Hostname  string `opt:"hostname"`
	UserAgent string `opt:"user_agent"`

	// Duration of time between heartbeats. This must be less than ReadTimeout
	HeartbeatInterval time.Duration `opt:"heartbeat_interval" default:"30s"`
	// Integer percentage to sample the channel (requires nsqd 0.2.25+)
	SampleRate int32 `opt:"sample_rate" min:"0" max:"99"`

	Tls *Tls `yaml:"tls" json:"tls"`

	// Compression Settings
	Deflate      bool `opt:"deflate"`
	DeflateLevel int  `opt:"deflate_level" min:"1" max:"9" default:"6"`
	Snappy       bool `opt:"snappy"`

	// Size of the buffer (in bytes) used by nsqd for buffering writes to this connection
	OutputBufferSize int64 `opt:"output_buffer_size" default:"16384"`
	// Timeout used by nsqd before flushing buffered writes (set to 0 to disable).
	//
	// WARNING: configuring clients with an extremely low
	// (< 25ms) output_buffer_timeout has a significant effect
	// on nsqd CPU usage (particularly with > 50 clients connected).
	OutputBufferTimeout time.Duration `opt:"output_buffer_timeout" default:"250ms"`

	// Maximum number of messages to allow in flight (concurrency knob)
	MaxInFlight int `opt:"max_in_flight" min:"0" default:"1"`

	// The server-side message timeout for messages delivered to this client
	MsgTimeout time.Duration `opt:"msg_timeout" min:"0"`

	// secret for nsqd authentication (requires nsqd 0.2.29+)
	AuthSecret string `opt:"auth_secret"`
}

func (NSQOptions) GetNSQOptions

func (e NSQOptions) GetNSQOptions() (*nsq.Config, error)

type ProducerConfig added in v1.1.19

type ProducerConfig struct {
	RequiredAcks   int           `mapstructure:"requiredAcks"`   // 消息确认级别 (0=不确认, 1=leader确认, -1=所有副本确认)
	FlushFrequency time.Duration `mapstructure:"flushFrequency"` // 刷新频率
	FlushMessages  int           `mapstructure:"flushMessages"`  // 批量消息数
	Timeout        time.Duration `mapstructure:"timeout"`        // 发送超时时间

}

ProducerConfig 生产者配置 - 用户配置层(简化) 只包含用户需要关心的核心配置字段 注意:压缩配置已从 Producer 级别移到 Topic 级别,通过 TopicBuilder 配置

type PublisherBacklogDetectionConfig added in v1.1.19

type PublisherBacklogDetectionConfig struct {
	Enabled           bool          `mapstructure:"enabled"`
	MaxQueueDepth     int64         `mapstructure:"maxQueueDepth"`     // 最大队列深度
	MaxPublishLatency time.Duration `mapstructure:"maxPublishLatency"` // 最大发送延迟
	RateThreshold     float64       `mapstructure:"rateThreshold"`     // 发送速率阈值 (msg/sec)
	CheckInterval     time.Duration `mapstructure:"checkInterval"`     // 检测间隔
}

PublisherBacklogDetectionConfig 发送端积压检测配置

type PublisherConfig added in v1.1.19

type PublisherConfig struct {
	// 重连配置
	MaxReconnectAttempts int           `mapstructure:"maxReconnectAttempts"` // 最大重连尝试次数(默认5次)
	InitialBackoff       time.Duration `mapstructure:"initialBackoff"`       // 初始退避时间(默认1秒)
	MaxBackoff           time.Duration `mapstructure:"maxBackoff"`           // 最大退避时间(默认30秒)

	// 发布配置
	PublishTimeout time.Duration `mapstructure:"publishTimeout"` // 发布超时(默认10秒)

	// 企业特性
	BacklogDetection PublisherBacklogDetectionConfig `mapstructure:"backlogDetection"` // 发送端积压检测
	RateLimit        RateLimitConfig                 `mapstructure:"rateLimit"`        // 流量控制
	ErrorHandling    ErrorHandlingConfig             `mapstructure:"errorHandling"`    // 错误处理
}

PublisherConfig 发布端配置

type Queue

type Queue struct {
	Redis  *QueueRedis  `mapstructure:"redis"`
	Memory *QueueMemory `mapstructure:"memory"`
	NSQ    *QueueNSQ    `mapstructure:"nsq" json:"nsq"`
}

Queue 队列配置

func (Queue) Empty

func (e Queue) Empty() bool

Empty 空设置

func (Queue) Setup

func (e Queue) Setup() (storage.AdapterQueue, error)

Setup 启用顺序 redis > 其他 > memory

type QueueMemory

type QueueMemory struct {
	PoolSize uint
}

type QueueNSQ

type QueueNSQ struct {
	NSQOptions
	ChannelPrefix string
}

type QueueRedis

type QueueRedis struct {
	RedisConnectOptions
	Producer *redisqueue.ProducerOptions
	Consumer *redisqueue.ConsumerOptions
}

type RateLimitConfig added in v1.1.19

type RateLimitConfig struct {
	Enabled       bool    `mapstructure:"enabled"`
	RatePerSecond float64 `mapstructure:"ratePerSecond"`
	BurstSize     int     `mapstructure:"burstSize"`
}

RateLimitConfig 流量控制配置

type Redis added in v1.1.10

type Redis struct {
	Addr     string `mapstructure:"addr"`
	Password string `mapstructure:"password"`
	DB       int    `mapstructure:"db"`
}

Redis Redis配置

type RedisConnectOptions

type RedisConnectOptions struct {
	Network    string `mapstructure:"network" json:"network"`
	Addr       string `mapstructure:"addr" json:"addr"`
	Username   string `mapstructure:"username" json:"username"`
	Password   string `mapstructure:"password" json:"password"`
	DB         int    `mapstructure:"db" json:"db"`
	PoolSize   int    `mapstructure:"pool_size" json:"pool_size"`
	Tls        *Tls   `mapstructure:"tls" json:"tls"`
	MaxRetries int    `mapstructure:"max_retries" json:"max_retries"`
}

func (RedisConnectOptions) GetRedisOptions

func (e RedisConnectOptions) GetRedisOptions() (*redis.Options, error)

type Register added in v1.1.10

type Register struct {
	Sources  []string `mapstructure:"sources"`
	Replicas []string `mapstructure:"replicas"`
	Policy   string   `mapstructure:"policy"`
	Tables   []string `mapstructure:"tables"`
}

type Resolver added in v1.1.11

type Resolver struct {
	Type       string `mapstructure:"type"`       // 租户识别方式: host, path, header, query
	HeaderName string `mapstructure:"headerName"` // 当type为header时使用的header名称
	QueryParam string `mapstructure:"queryParam"` // 当type为query时使用的查询参数名
	PathIndex  int    `mapstructure:"pathIndex"`  // 当type为path时使用的路径索引
}

Resolver 租户识别配置

type SSL added in v1.1.10

type SSL struct {
	KeyStr string `mapstructure:"key_str"` // 私钥内容(字符串形式)
	Pem    string `mapstructure:"pem"`     // 证书内容(PEM格式,字符串形式)
	Enable bool   `mapstructure:"enable"`  // 是否启用安全连接
	Domain string `mapstructure:"domain"`  // 证书域名(用于生成证书)
}

type SSLConfig added in v1.1.10

type SSLConfig struct {
	Enabled bool   `mapstructure:"enabled" json:"enabled"` // 是否启用HTTPS
	KeyStr  string `mapstructure:"key_str"`                // 私钥内容(字符串形式)
	Pem     string `mapstructure:"pem"`                    // 证书内容(PEM格式,字符串形式)
	Domain  string `mapstructure:"domain"`                 // 证书域名(用于生成证书)
}

SSLConfig SSL/TLS配置

type SecurityConfig added in v1.1.19

type SecurityConfig struct {
	Enabled  bool   `mapstructure:"enabled"`
	Protocol string `mapstructure:"protocol"`
	Username string `mapstructure:"username"`
	Password string `mapstructure:"password"`
	CertFile string `mapstructure:"certFile"`
	KeyFile  string `mapstructure:"keyFile"`
	CAFile   string `mapstructure:"caFile"`
}

SecurityConfig 安全配置

type ServerMiddlewaresConfig added in v1.1.18

type ServerMiddlewaresConfig struct {
	Trace      bool `mapstructure:"trace" json:"trace,default=true"`           // 链路跟踪
	Recover    bool `mapstructure:"recover" json:"recover,default=true"`       // 异常恢复
	Stat       bool `mapstructure:"stat" json:"stat,default=true"`             // 统计
	Prometheus bool `mapstructure:"prometheus" json:"prometheus,default=true"` // Prometheus监控
	Breaker    bool `mapstructure:"breaker" json:"breaker,default=true"`       // 熔断器
}

ServerMiddlewaresConfig 服务端中间件配置

type ServiceConfig added in v1.1.10

type ServiceConfig struct {
	Enabled      bool     `mapstructure:"enabled" json:"enabled,default=true"`       // 服务启用状态
	Interceptors []string `mapstructure:"interceptors" json:"interceptors,optional"` // 拦截器列表
}

ServiceConfig 服务配置

type StreamConfig added in v1.1.19

type StreamConfig struct {
	Name      string        `mapstructure:"name"`
	Subjects  []string      `mapstructure:"subjects"`
	Retention string        `mapstructure:"retention"` // limits, interest, workqueue
	Storage   string        `mapstructure:"storage"`   // file, memory
	Replicas  int           `mapstructure:"replicas"`
	MaxAge    time.Duration `mapstructure:"maxAge"`
	MaxBytes  int64         `mapstructure:"maxBytes"`
	MaxMsgs   int64         `mapstructure:"maxMsgs"`
	Discard   string        `mapstructure:"discard"` // old, new
}

StreamConfig 流配置

type SubscriberBacklogDetectionConfig added in v1.1.19

type SubscriberBacklogDetectionConfig struct {
	Enabled          bool          `mapstructure:"enabled"`
	MaxLagThreshold  int64         `mapstructure:"maxLagThreshold"`  // 最大消息积压数量
	MaxTimeThreshold time.Duration `mapstructure:"maxTimeThreshold"` // 最大积压时间
	CheckInterval    time.Duration `mapstructure:"checkInterval"`    // 检测间隔
}

SubscriberBacklogDetectionConfig 订阅端积压检测配置

type SubscriberConfig added in v1.1.19

type SubscriberConfig struct {
	// 消费配置
	MaxConcurrency int           `mapstructure:"maxConcurrency"` // 最大并发数(默认10)
	ProcessTimeout time.Duration `mapstructure:"processTimeout"` // 处理超时(默认30秒)

	// 企业特性
	BacklogDetection SubscriberBacklogDetectionConfig `mapstructure:"backlogDetection"` // 订阅端积压检测
	RateLimit        RateLimitConfig                  `mapstructure:"rateLimit"`        // 流量控制
	ErrorHandling    ErrorHandlingConfig              `mapstructure:"errorHandling"`    // 错误处理
}

SubscriberConfig 订阅端配置

type TLSConfig added in v1.1.10

type TLSConfig struct {
	Enabled bool   `mapstructure:"enabled" json:"enabled,optional"` // 是否启用TLS
	KeyStr  string `mapstructure:"key_str" json:"key_str,optional"` // 私钥内容
	Pem     string `mapstructure:"pem" json:"pem,optional"`         // 证书内容
	Domain  string `mapstructure:"domain" json:"domain,optional"`   // 证书域名
}

TLSConfig TLS配置

type TenantConfig added in v1.1.11

type TenantConfig struct {
	ID       string   `mapstructure:"id"`       //租户ID,唯一标识一个租户
	Name     string   `mapstructure:"name"`     //租户名称,便于识别和管理
	Active   bool     `mapstructure:"active"`   //租户是否处于活动状态
	Hosts    []string `mapstructure:"hosts"`    //允许一个租户关联多个主机名(域名/子域名)提供了显著的灵活性和业务价值
	Database Database `mapstructure:"database"` //租户数据库配置
}

type Tenants added in v1.1.11

type Tenants struct {
	Enabled bool `mapstructure:"enabled"` //是否启用租户配置
	//默认配置的作用:
	//1.每个租户只需配置与默认值不同的部分,大幅减少配置文件的体积和复杂度;
	//2.为所有租户提供一个基准配置,确保关键参数的一致性。
	//3.当需要更改通用配置时,只需修改默认值而非每个租户的配置。
	//4.当租户特定配置缺失或无效时,系统可以平滑降级到默认配置。
	Resolver Resolver       `mapstructure:"resolver"`
	Defaults DefaultConfig  `mapstructure:"defaults"`
	List     []TenantConfig `mapstructure:"list"` //租户列表
}

type Tls

type Tls struct {
	Cert string `mapstructure:"cert" json:"cert"`
	Key  string `mapstructure:"key" json:"key"`
	Ca   string `mapstructure:"ca" json:"ca"`
}

type TracingConfig added in v1.1.19

type TracingConfig struct {
	Enabled     bool    `mapstructure:"enabled"`
	ServiceName string  `mapstructure:"serviceName"`
	Endpoint    string  `mapstructure:"endpoint"`
	SampleRate  float64 `mapstructure:"sampleRate"`
}

TracingConfig 链路追踪配置

Jump to

Keyboard shortcuts

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