redis

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Jun 4, 2025 License: MIT Imports: 6 Imported by: 5

README

Redis Provider

Redis provider cung cấp quản lý kết nối Redis và hỗ trợ dependency injection cho ứng dụng Go.

Tổng quan

Package này cung cấp một cách đơn giản để cấu hình và quản lý các kết nối Redis trong ứng dụng Go. Nó hỗ trợ:

  • Redis client tiêu chuẩn
  • Universal client cho Redis Cluster, Sentinel và triển khai standalone
  • Dependency injection thông qua container Fork/di
  • Cấu hình thông qua package Fork/providers/config
  • Kiểm thử dễ dàng với hỗ trợ mock (sử dụng mockery)

Cài đặt

go get go.fork.vn/redis

Sử dụng

Sử dụng cơ bản
import (
    "context"
    "go.fork.vn/redis"
)

func main() {
    // Khởi tạo Redis manager với cấu hình mặc định
    manager := redis.NewManager()
    
    // Hoặc với cấu hình tùy chỉnh
    config := redis.DefaultConfig()
    config.Client.Host = "redis-server"
    config.Client.Port = 6379
    manager = redis.NewManagerWithConfig(config)
    
    // Lấy Redis client
    client, err := manager.Client()
    if err != nil {
        // Xử lý lỗi
    }
    
    // Sử dụng client để thực hiện các thao tác Redis
    ctx := context.Background()
    err = client.Set(ctx, "key", "value", 0).Err()
    if err != nil {
        // Xử lý lỗi
    }
    
    // Kiểm tra kết nối
    err = manager.Ping(ctx)
    if err != nil {
        // Xử lý lỗi kết nối
    }
}
Sử dụng với Dependency Injection
import (
    "go.fork.vn/di"
    "go.fork.vn/redis"
    "go.fork.vn/config"
)

// Định nghĩa một ứng dụng với container DI
type App struct {
    container *di.Container
}

func (a *App) Container() *di.Container {
    return a.container
}

func main() {
    // Khởi tạo container và app
    container := di.New()
    app := &App{container: container}
    
    // Đăng ký config provider trước
    configProvider := config.NewServiceProvider()
    configProvider.Register(app)
    
    // Đăng ký Redis provider
    redisProvider := redis.NewServiceProvider()
    redisProvider.Register(app)
    
    // Khởi động các provider
    configProvider.Boot(app)
    redisProvider.Boot(app)
    
    // Sau khi provider được đăng ký và khởi động, bạn có thể lấy Redis client:
    redisClient, err := container.Make("redis.client")
    if err != nil {
        // Xử lý lỗi
    }
    
    universalClient, err := container.Make("redis.universal")
    if err != nil {
        // Xử lý lỗi
    }
    
    manager, err := container.Make("redis.manager")
    if err != nil {
        // Xử lý lỗi
    }
}
Cấu hình

Tạo file redis.yaml trong thư mục cấu hình của bạn:

redis:
  # Cấu hình client tiêu chuẩn
  client:
    enabled: true
    host: localhost
    port: 6379
    password: ""
    db: 0
    prefix: "app:"
    timeout: 5  # seconds
    dial_timeout: 5  # seconds
    read_timeout: 3  # seconds
    write_timeout: 3  # seconds
    pool_size: 10
    min_idle_conns: 5
  
  # Cấu hình universal client (cho cluster/sentinel/standalone)
  universal:
    enabled: false
    addresses:
      - localhost:6379
    password: ""
    db: 0
    prefix: "app:"
    timeout: 5  # seconds
    dial_timeout: 5  # seconds
    read_timeout: 3  # seconds
    write_timeout: 3  # seconds
    max_retries: 3
    min_retry_backoff: 8  # milliseconds
    max_retry_backoff: 512  # milliseconds
    pool_size: 10
    min_idle_conns: 5
    
    # Cấu hình cho Cluster mode
    cluster_mode: false
    max_redirects: 3
    
    # Cấu hình cho Sentinel mode
    sentinel_mode: false
    master_name: "mymaster"
Testing với Mock

Package này hỗ trợ mocking thông qua Mockery:

import (
    "testing"
    
    "go.fork.vn/redis"
    "go.fork.vn/redis/mocks"
    "github.com/stretchr/testify/assert"
)

func TestWithMockRedisManager(t *testing.T) {
    // Tạo mock cho Redis manager
    mockManager := mocks.NewMockManager(t)
    
    // Thiết lập expectation
    mockManager.EXPECT().Ping(mock.Anything).Return(nil)
    
    // Sử dụng mock trong test
    err := mockManager.Ping(context.Background())
    assert.NoError(t, err)
    
    // Kiểm tra xem tất cả các expectation có được gọi không
    mockManager.AssertExpectations(t)
}

Đóng góp

Nếu bạn phát hiện lỗi hoặc có ý tưởng cải thiện, vui lòng tạo issue hoặc pull request trên GitHub.

Giấy phép

Package này được cấp phép theo Giấy phép MIT.

Documentation

Overview

Package redis cung cấp một trình quản lý kết nối Redis và service provider cho các ứng dụng Go.

Tổng quan

Package này giúp quản lý các kết nối Redis và cung cấp chúng thông qua dependency injection. Nó triển khai cả Redis client tiêu chuẩn và universal client có thể được sử dụng cho triển khai Redis Cluster, Sentinel và standalone.

Thành phần chính

  • Manager: Interface chính để quản lý kết nối Redis, cung cấp các phương thức để tạo và quản lý các kết nối, bao gồm standard client và universal client.

  • ServiceProvider: Tích hợp với DI container để đăng ký các dịch vụ Redis.

  • Config: Cấu hình cho Redis client và universal client, hỗ trợ tất cả các tùy chọn kết nối.

Sử dụng cơ bản

// Khởi tạo Redis manager với cấu hình mặc định
manager := redis.NewManager()

// Lấy Redis client
client, err := manager.Client()
if err != nil {
    // Xử lý lỗi
}

// Sử dụng client để thực hiện các thao tác Redis
err = client.Set(ctx, "key", "value", 0).Err()

Tích hợp với DI Container

// Tạo service provider
provider := redis.NewServiceProvider()

// Đăng ký provider với ứng dụng
provider.Register(app)

Phụ thuộc

Package này phụ thuộc vào:

  • go.fork.vn/config cho quản lý cấu hình
  • go.fork.vn/di cho dependency injection
  • github.com/redis/go-redis/v9 cho Redis client

Khả năng tùy chỉnh

Cung cấp nhiều tùy chọn cấu hình cho Redis client như:

  • Địa chỉ máy chủ, cổng kết nối
  • Xác thực (mật khẩu)
  • Timeout và các tham số kết nối
  • Cấu hình cluster và sentinel
  • Tiền tố khóa

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ClientConfig

type ClientConfig struct {
	// Enabled xác định liệu Redis Standard Client có được kích hoạt hay không.
	Enabled bool `mapstructure:"enabled"`

	// Host là địa chỉ máy chủ Redis.
	Host string `mapstructure:"host"`

	// Port là cổng kết nối của máy chủ Redis.
	Port int `mapstructure:"port"`

	// Password là mật khẩu xác thực với máy chủ Redis.
	Password string `mapstructure:"password"`

	// DB là số của database Redis sẽ được sử dụng.
	DB int `mapstructure:"db"`

	// Prefix là tiền tố sẽ được thêm vào tất cả các khóa.
	Prefix string `mapstructure:"prefix"`

	// Timeout là thời gian chờ chung cho các hoạt động Redis.
	Timeout int `mapstructure:"timeout"` // seconds

	// DialTimeout là thời gian chờ khi thiết lập kết nối tới Redis.
	DialTimeout int `mapstructure:"dial_timeout"` // seconds

	// ReadTimeout là thời gian chờ khi đọc dữ liệu từ Redis.
	ReadTimeout int `mapstructure:"read_timeout"` // seconds

	// WriteTimeout là thời gian chờ khi ghi dữ liệu vào Redis.
	WriteTimeout int `mapstructure:"write_timeout"` // seconds

	// PoolSize là số lượng kết nối tối đa được giữ trong pool.
	PoolSize int `mapstructure:"pool_size"`

	// MinIdleConns là số lượng kết nối rảnh tối thiểu được giữ trong pool.
	MinIdleConns int `mapstructure:"min_idle_conns"`
}

ClientConfig chứa cấu hình cho Redis Standard Client.

func (*ClientConfig) GetClientOptions

func (c *ClientConfig) GetClientOptions() *ClientOptions

GetClientOptions trả về Redis Client Options từ cấu hình.

type ClientOptions

type ClientOptions struct {
	Addr         string
	Password     string
	DB           int
	DialTimeout  time.Duration
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
	PoolSize     int
	MinIdleConns int
}

ClientOptions là wrapper cho Redis Client Options.

type Config

type Config struct {
	// Client là cấu hình cho Redis Standard Client.
	Client *ClientConfig `mapstructure:"client"`

	// Universal là cấu hình cho Redis Universal Client (hỗ trợ Cluster, Sentinel, và standalone).
	Universal *UniversalConfig `mapstructure:"universal"`
}

Config là cấu trúc dữ liệu cấu hình chính cho Redis.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig trả về cấu hình mặc định cho Redis.

type Manager

type Manager interface {
	// Client trả về một Redis Client mới hoặc đã lưu trong cache.
	Client() (*redis.Client, error)

	// UniversalClient trả về một Redis Universal Client mới hoặc đã lưu trong cache.
	UniversalClient() (*redis.UniversalClient, error)

	// GetConfig trả về cấu hình hiện tại của Manager.
	GetConfig() *Config

	// Close đóng tất cả các kết nối Redis.
	Close() error

	// Ping kiểm tra kết nối tới Redis server.
	Ping(ctx context.Context) error

	// ClusterPing kiểm tra kết nối tới Redis Cluster.
	ClusterPing(ctx context.Context) error
}

Manager là interface chính để quản lý kết nối Redis.

Manager cung cấp các phương thức để tạo và quản lý các kết nối Redis, bao gồm cả standard client và universal client.

func NewManager

func NewManager(config *Config) Manager

NewManager tạo một Manager mới với cấu hình mặc định.

type ServiceProvider

type ServiceProvider interface {
	di.ServiceProvider
}

ServiceProvider định nghĩa interface cho Redis service provider.

ServiceProvider kế thừa từ di.ServiceProvider và định nghĩa các phương thức cần thiết cho một Redis service provider.

func NewServiceProvider

func NewServiceProvider() ServiceProvider

NewServiceProvider tạo một Redis service provider mới.

type UniversalConfig

type UniversalConfig struct {
	// Enabled xác định liệu Redis Universal Client có được kích hoạt hay không.
	Enabled bool `mapstructure:"enabled"`

	// Addresses là danh sách các địa chỉ máy chủ Redis (host:port)
	Addresses []string `mapstructure:"addresses"`

	// Password là mật khẩu xác thực với máy chủ Redis.
	Password string `mapstructure:"password"`

	// DB là số của database Redis sẽ được sử dụng.
	DB int `mapstructure:"db"`

	// Prefix là tiền tố sẽ được thêm vào tất cả các khóa.
	Prefix string `mapstructure:"prefix"`

	// Timeout là thời gian chờ chung cho các hoạt động Redis.
	Timeout int `mapstructure:"timeout"` // seconds

	// DialTimeout là thời gian chờ khi thiết lập kết nối tới Redis.
	DialTimeout int `mapstructure:"dial_timeout"` // seconds

	// ReadTimeout là thời gian chờ khi đọc dữ liệu từ Redis.
	ReadTimeout int `mapstructure:"read_timeout"` // seconds

	// WriteTimeout là thời gian chờ khi ghi dữ liệu vào Redis.
	WriteTimeout int `mapstructure:"write_timeout"` // seconds

	// MaxRetries là số lần thử lại tối đa cho các thao tác lỗi.
	MaxRetries int `mapstructure:"max_retries"`

	// MinRetryBackoff là thời gian chờ tối thiểu giữa các lần thử lại (milliseconds).
	MinRetryBackoff int `mapstructure:"min_retry_backoff"` // milliseconds

	// MaxRetryBackoff là thời gian chờ tối đa giữa các lần thử lại (milliseconds).
	MaxRetryBackoff int `mapstructure:"max_retry_backoff"` // milliseconds

	// PoolSize là số lượng kết nối tối đa được giữ trong pool.
	PoolSize int `mapstructure:"pool_size"`

	// MinIdleConns là số lượng kết nối rảnh tối thiểu được giữ trong pool.
	MinIdleConns int `mapstructure:"min_idle_conns"`

	// ClusterMode xác định liệu Universal Client có chạy ở chế độ Cluster hay không.
	ClusterMode bool `mapstructure:"cluster_mode"`

	// MaxRedirects là số lần chuyển hướng tối đa cho các thao tác cluster.
	MaxRedirects int `mapstructure:"max_redirects"`

	// SentinelMode xác định liệu Universal Client có chạy ở chế độ Sentinel hay không.
	SentinelMode bool `mapstructure:"sentinel_mode"`

	// MasterName là tên của master đang được giám sát bởi các máy chủ sentinel.
	MasterName string `mapstructure:"master_name"`
}

UniversalConfig chứa cấu hình cho Redis Universal Client.

func (*UniversalConfig) GetUniversalOptions

func (c *UniversalConfig) GetUniversalOptions() *UniversalOptions

GetUniversalOptions trả về Redis Universal Client Options từ cấu hình.

type UniversalOptions

type UniversalOptions struct {
	Addrs           []string
	MasterName      string
	Password        string
	DB              int
	DialTimeout     time.Duration
	ReadTimeout     time.Duration
	WriteTimeout    time.Duration
	MaxRetries      int
	MinRetryBackoff time.Duration
	MaxRetryBackoff time.Duration
	PoolSize        int
	MinIdleConns    int
	RouteRandomly   bool
}

UniversalOptions là wrapper cho Redis Universal Client Options.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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