memcached

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 15, 2026 License: MIT Imports: 9 Imported by: 0

README

Compogo Memcached 📦

Compogo Memcached — это полноценный Memcached-клиент для Compogo, построенный поверх популярной библиотеки bradfitz/gomemcache. Предоставляет полный API оригинальной библиотеки, настраивается через флаги и может использоваться как самостоятельный кэш или как драйвер для централизованной системы кэширования Compogo Cache.

🚀 Установка

go get github.com/Compogo/memcached
📦 Быстрый старт
package main

import (
    "github.com/Compogo/compogo"
    "github.com/Compogo/memcached"
    "github.com/bradfitz/gomemcache/memcache"
)

func main() {
    app := compogo.NewApp("myapp",
        compogo.WithOsSignalCloser(),
        memcached.Component,  // добавляем Memcached-клиент
        compogo.WithComponents(
            userServiceComponent,
        ),
    )

    if err := app.Serve(); err != nil {
        panic(err)
    }
}

// Использование в сервисе
var userServiceComponent = &component.Component{
    Dependencies: component.Components{memcached.Component},
    Execute: component.StepFunc(func(c container.Container) error {
        return c.Invoke(func(cache memcached.Cache) {
            service := &UserService{cache: cache}
            service.Start()
        })
    }),
}

type UserService struct {
    cache memcached.Cache
}

func (s *UserService) GetUser(ctx context.Context, id int) (*User, error) {
    // Пытаемся достать из кэша
    item, err := s.cache.Get(fmt.Sprintf("user:%d", id))
    if err == nil {
        var user User
        json.Unmarshal(item.Value, &user)
        return &user, nil
    }
    
    // Нет в кэше — грузим из БД
    user, err := s.db.LoadUser(id)
    if err != nil {
        return nil, err
    }
    
    // Кладём в кэш
    data, _ := json.Marshal(user)
    s.cache.Set(&memcache.Item{
        Key:        fmt.Sprintf("user:%d", id),
        Value:      data,
        Expiration: 300, // 5 минут
    })
    
    return user, nil
}
✨ Возможности
🎯 Полный API gomemcache

Интерфейс Cache повторяет все методы оригинальной библиотеки:

// Базовые операции
cache.Set(&memcache.Item{Key: "key", Value: data})
item, err := cache.Get("key")
cache.Delete("key")

// Множественное чтение
items, err := cache.GetMulti([]string{"key1", "key2"})

// Атомарные операции
newVal, _ := cache.Increment("counter", 1)
newVal, _ := cache.Decrement("counter", 1)

// Условное обновление
err := cache.CompareAndSwap(&memcache.Item{
    Key:        "key",
    Value:      newData,
    Expiration: 300,
})

// Модификация данных
cache.Append(&memcache.Item{Key: "log", Value: []byte("new line")})
cache.Prepend(&memcache.Item{Key: "log", Value: []byte("header")})

// Управление сроком жизни
cache.Touch("key", 600) // продлить на 10 минут

// Проверка подключения
err := cache.Ping()

// Массовые операции
cache.FlushAll()   // очистить всё
cache.DeleteAll()  // удалить всё
🔌 Два способа использования
Как самостоятельный Memcached-клиент:
type Service struct {
    cache memcached.Cache  // через интерфейс
    // или
    raw *memcache.Client    // напрямую
}
Как драйвер для централизованной системы кэширования:
import (
    "github.com/Compogo/cache"
    "github.com/Compogo/memcached/registration"
)

app := compogo.NewApp("myapp",
    cache.Component,
    memcached.Component,
    registration.Component,  // регистрирует "memcached" драйвер
)

// Теперь можно использовать через cache.CacheInterface[[]byte]
// с флагом --cache.driver=memcached

Documentation

Index

Constants

View Source
const (
	HostsFieldName     = "cache.memcached.hosts"
	MaxIdleConnections = "cache.memcached.maxIdleConnections"
	TimeoutFieldName   = "cache.memcached.timeout"

	MaxIdleConnectionsDefault = memcache.DefaultMaxIdleConns
	TimeoutDefault            = memcache.DefaultTimeout
)

Variables

View Source
var Component = &component.Component{
	Init: component.StepFunc(func(container container.Container) error {
		return container.Provides(
			NewConfig,
			NewCache,
			func(cache *memcache.Client) Cache { return cache },
		)
	}),
	BindFlags: component.BindFlags(func(flagSet flag.FlagSet, container container.Container) error {
		return container.Invoke(func(config *Config) {
			flagSet.StringSliceVar(&config.Hosts, HostsFieldName, HostsDefault, "memcached connection hosts")
			flagSet.Uint16Var(&config.MaxIdleConnections, MaxIdleConnections, MaxIdleConnectionsDefault, "maximum number of idle connections")
			flagSet.DurationVar(&config.Timeout, TimeoutFieldName, TimeoutDefault, "socket read/write timeout")
		})
	}),
	Configuration: component.StepFunc(func(container container.Container) error {
		return container.Invoke(Configuration)
	}),
}

Component is a ready-to-use Compogo component that provides a Memcached client. It automatically:

  • Registers Config and Client in the DI container
  • Adds command-line flags for Memcached configuration
  • Configures the client during Configuration phase
  • Provides the client as both *memcache.Client and Cache interface

Usage:

compogo.WithComponents(
    memcached.Component,
    // ... your service components
)

Then in your service:

type Service struct {
    cache memcached.Cache  // or *memcache.Client
}
View Source
var HostsDefault = []string{"localhost:11211"}

Functions

func NewCache

func NewCache(config *Config, informer logger.Informer) *memcache.Client

NewCache creates a new Memcached client instance. It initializes the underlying gomemcache client with the configured hosts, connection pool size, and timeout settings.

The informer is used to log the configuration for debugging purposes. Returns a configured memcache.Client ready for use.

Types

type Cache

type Cache interface {
	Add(item *memcache.Item) error
	Append(item *memcache.Item) error
	CompareAndSwap(item *memcache.Item) error
	Decrement(key string, delta uint64) (newValue uint64, err error)
	Delete(key string) error
	DeleteAll() error
	FlushAll() error
	Get(key string) (item *memcache.Item, err error)
	GetMulti(keys []string) (map[string]*memcache.Item, error)
	Increment(key string, delta uint64) (newValue uint64, err error)
	Ping() error
	Prepend(item *memcache.Item) error
	Replace(item *memcache.Item) error
	Set(item *memcache.Item) error
	Touch(key string, seconds int32) (err error)
}

Cache defines the complete interface for Memcached operations. It mirrors the full API of bradfitz/gomemcache to provide maximum flexibility.

The interface includes methods for:

  • Basic operations: Set, Get, Delete
  • Atomic operations: Increment, Decrement, CompareAndSwap
  • Multi-key operations: GetMulti
  • Batch operations: DeleteAll, FlushAll
  • Connection management: Ping
  • Expiration management: Touch
  • Data modification: Append, Prepend

type Config

type Config struct {
	Hosts              []string
	MaxIdleConnections uint16
	Timeout            time.Duration
}

func Configuration

func Configuration(config *Config, configurator configurator.Configurator) *Config

func NewConfig

func NewConfig() *Config

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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