Nats
一个 NATS 键值存储驱动程序。
注意:需要 Go 1.20 及以上版本
目录
签名
func New(config ...Config) Storage
func (s *Storage) Get(key string) ([]byte, error)
func (s *Storage) Set(key string, val []byte, exp time.Duration) error
func (s *Storage) Delete(key string) error
func (s *Storage) Reset() error
func (s *Storage) Close() error
func (s *Storage) Conn() (*nats.Conn, jetstream.KeyValue)
func (s *Storage) Keys() ([]string, error)
安装
NATS 键值存储 驱动程序在最新的两个 Go 版本 上进行了测试,并支持模块。因此,如果您尚未初始化模块,请确保先初始化一个。
go mod init github.com/<user>/<repo>
然后安装 nats 实现
go get github.com/gofiber/storage/nats
示例
导入存储包。
import "github.com/gofiber/storage/nats"
您可以使用以下选项创建存储驱动程序
// Initialize default config
store := nats.New()
// Initialize custom config
store := nats.New(Config{
URLs: "nats://127.0.0.1:4443",
NatsOptions: []nats.Option{
nats.MaxReconnects(2),
// Enable TLS by specifying RootCAs
nats.RootCAs("./testdata/certs/ca.pem"),
},
KeyValueConfig: jetstream.KeyValueConfig{
Bucket: "test",
Storage: jetstream.MemoryStorage,
},
})
配置
type Config struct {
// Nats URLs, default "nats://127.0.0.1:4222". Can be comma separated list for multiple servers
URLs string
// Nats connection options. See nats_test.go for an example of how to use this.
NatsOptions []nats.Option
// Nats connection name
ClientName string
// Nats context
Context context.Context
// Nats key value config
KeyValueConfig jetstream.KeyValueConfig
// Wait for connection to be established, default: 100ms
WaitForConnection time.Duration
}
默认配置
var ConfigDefault = Config{
URLs: nats.DefaultURL,
Context: context.Background(),
ClientName: "fiber_storage",
KeyValueConfig: jetstream.KeyValueConfig{
Bucket: "fiber_storage",
},
WaitForConnection: 100 * time.Millisecond,
}