memcached

package module
v1.0.0-rc1 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2026 License: MIT Imports: 6 Imported by: 0

README

Compogo Memcached

Адаптер Memcached для фреймворка Compogo.

На основе gomemcache предоставляет:

  • Клиент для работы с Memcached
  • Поддержку множества хостов
  • Настройку пула соединений
  • Интеграцию с 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.WithComponents(&memcached.Component),
    )

    app.AddComponents(&compogo.Component{
        Name: "my_service",
        Init: compogo.StepFunc(func(container compogo.Container) error {
            return container.Invoke(func(c memcached.Cache) error {
                // Сохранение
                err := c.Set(&memcache.Item{
                    Key:   "user:123",
                    Value: []byte(`{"name":"John"}`),
                })
                if err != nil {
                    return err
                }

                // Чтение
                item, err := c.Get("user:123")
                if err != nil {
                    return err
                }
                println(string(item.Value))

                return nil
            })
        }),
    })

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

Конфигурация

Флаги командной строки
# Хосты Memcached
--cache.memcached.hosts=localhost:11211,10.0.0.1:11211

# Максимальное количество простаивающих соединений
--cache.memcached.maxIdleConnections=10

# Таймаут операций
--cache.memcached.timeout=100ms

Интеграция с Compogo Cache

import (
    "github.com/Compogo/memcached/registration"
)

func main() {
    app := compogo.NewApp("myapp",
        compogo.WithComponents(&registration.Component),
    )
    // Теперь cache.NewCache() использует Memcached
}

Зависимости

  • Compogo — основной фреймворк
  • gomemcache — клиент Memcached

Лицензия

MIT License

Copyright (c) 2026 Compogo

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Documentation

Index

Constants

View Source
const (
	// HostsFieldName хосты Memcached
	HostsFieldName = "cache.memcached.hosts"

	// MaxIdleConnections максимальное число простаивающих соединений
	MaxIdleConnections = "cache.memcached.maxIdleConnections"

	// TimeoutFieldName таймаут операций
	TimeoutFieldName = "cache.memcached.timeout"
)

Variables

View Source
var (
	HostsDefault              = []string{"localhost:11211"}
	MaxIdleConnectionsDefault = uint16(memcache.DefaultMaxIdleConns)
	TimeoutDefault            = memcache.DefaultTimeout
)
View Source
var Component = compogo.Component{
	Init: compogo.StepFunc(func(container compogo.Container) error {
		return container.Provides(
			NewConfig,
			NewCache,
			func(cache *memcache.Client) Cache { return cache },
		)
	}),
	BindFlags: compogo.BindFlags(func(flagSet flag.FlagSet, container compogo.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: compogo.StepFunc(func(container compogo.Container) error {
		return container.Invoke(Configuration)
	}),
}

Component — компонент Memcached для Compogo. Регистрирует конфигурацию и клиент в DI-контейнере.

Пример подключения:

app.AddComponents(&memcached.Component)

var client memcached.Cache
container.Invoke(func(c memcached.Cache) { client = c })
client.Set(&memcache.Item{Key: "key", Value: []byte("value")})

Functions

func NewCache

func NewCache(config *Config, logger compogo.Logger) *memcache.Client

NewCache создаёт новый клиент Memcached. Настраивает хосты, максимальное количество простаивающих соединений и таймаут.

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 — интерфейс для работы с Memcached. Предоставляет все методы библиотеки gomemcache.

Поддерживает:

  • Базовые операции: Set, Get, Delete
  • Атомарные операции: Increment, Decrement, CompareAndSwap
  • Множественные операции: GetMulti
  • Администрирование: FlushAll, DeleteAll, Ping
  • Управление TTL: Touch

type Config

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

Config содержит конфигурацию Memcached.

func Configuration

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

Configuration загружает конфигурацию из Configurator. Если значения не заданы, устанавливаются значения по умолчанию.

func NewConfig

func NewConfig() *Config

NewConfig создаёт новую конфигурацию.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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