cache

package
v1.2.2 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2023 License: Apache-2.0 Imports: 18 Imported by: 0

README

介绍

wego/cache是用于存取应用缓存数据一个模块。缓存数据通常存储在缓存存储引擎中,wego/cache通过存储引擎提供的API来访问缓存数据。 缓存存储引擎通常采用内存来存储缓存数据,并且采用hash表来组织和管理缓存数据,因此缓存存储引擎通常具有比数据库更高的访问性能。 使用缓存可以提升应用的访问性能,并能够大大降低应用对数据库的访问压力。另外Web服务的session数据也多存储于缓存引擎中。 wego/cache支持目前支持三种缓存引擎:

  1. memcache
  2. redis
  3. memory 其中memory引擎使用本地内存来存储缓存数据,由于不需要通过网络来访问数据,memory引擎具有更高的访问性能。

安装

go get github.com/haming123/wego/cache

快速上手

实现看看如何使用memory引擎来存取缓存数据:

package main
import (
	"fmt"
	"wego/cache"
)
func main()  {
	cache.InitMemoryStore()

	err := cache.Set("name", "hello")
	if err != nil {
		fmt.Println(err)
		return
	}

	val_str, err := cache.GetString("name")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(val_str)

	err = cache.Delete("name")
	if err != nil {
		fmt.Println(err)
		return
	}
}

各种类型的数据的存取

为了方便各种类型的数据的存取, wego/cache提供了GetString、GetInt...等快捷函数:

func TestMemoryStoreDataType(t *testing.T) {
	cache.InitMemoryStore()

	cache.Set("str_val", "hello")
	t.Log(cache.GetString("str_val"))

	cache.Set("bool_val", true)
	t.Log(cache.GetBool("bool_val"))

	cache.Set("int_val", 111)
	t.Log(cache.GetInt("int_val"))

	cache.Set("float_val", 123.45)
	t.Log(cache.GetFloat("float_val"))

	cache.Set("time_val", time.Now())
	t.Log(cache.GetTime("time_val"))
}

存取结构体数据

wego/cache存储struct时,通过JSON序列化函数将结构体序列化为[]byte,然后将byte数组存储到存储引擎中。JSON序列化时只会序列化公开字段(大写开头的字段), 因此在使用wego/cache时需要确保不要使用非公开字段。用户也可以通过struct的tag来设定是否需要序列化一个字段,或者是为字段指定一个序列化名称。

func TestMemoryStoreStruct(t *testing.T) {
	type User struct {
		Name 	string
		Age 	int
	}
	user := User{Name:"lisi", Age:12}

	cache.InitMemoryStore()

	cache.Set("user", user)

	user2 := User{}
	err := cache.GetStuct("user", &user2)
	if err != nil {
		t.Error(err)
	}
	t.Log(user2)
}

设定数据的有效期

在使用Set方法存储缓存数据时,您可以为数据指定一个有效期(单位:秒)

func TestMemoryStoreMaxAge(t *testing.T) {
   cache.InitMemoryStore()

   err := cache.Set("name", "hello", 3)
   if err != nil {
   	t.Error(err)
   	return
   }

   val_str, err := cache.GetString("name")
   if err != nil {
   	t.Error(err)
   	return
   }
   t.Log(val_str)

   time.Sleep(3*time.Second)
   val_str, err = cache.GetString("name")
   if err != nil {
   	t.Error(err)
   	return
   }
   t.Log(val_str)
}

使用redis缓存数据

func TestStoreCacheRedis(t *testing.T) {
   cache.InitRedisStore("127.0.0.1:6379", "redis_pwd")

   err := cache.Set("name", "hello")
   if err != nil {
   	t.Error(err)
   	return
   }

   val_str, err := cache.GetString("name")
   if err != nil {
   	t.Error(err)
   	return
   }
   t.Log(val_str)

   err = cache.Delete("name")
   if err != nil {
   	t.Error(err)
   	return
   }
}

使用memcache缓存数据

func TestStoreCacheMemcache(t *testing.T) {
   cache.InitMemcacheStore("127.0.0.1:11211")

   err := cache.Set("name", "hello")
   if err != nil {
   	t.Error(err)
   	return
   }

   val_str, err := cache.GetString("name")
   if err != nil {
   	t.Error(err)
   	return
   }
   t.Log(val_str)

   err = cache.Delete("name")
   if err != nil {
   	t.Error(err)
   	return
   }
}

自定义存储引擎

wego/cache 模块采用了接口的方式来实现缓存功能,用户可以实现该缓存接口,从而使用自己的缓存引擎来存取缓存数据:

type CacheStore interface {
   SaveData(ctx context.Context, key string, data []byte, max_age uint) error
   ReadData(ctx context.Context, key string) ([]byte, error)
   Exist(ctx context.Context, key string) (bool, error)
   Delete(ctx context.Context, key string) error
}

要使用自定义的引擎,需要首先创建引擎对象,例如

store := &MyStroe{...}

然后通过cache.SetCacheStore设置存储引擎, 例如:

cache.SetCacheStore(store)

然后结可以使用相应的存取函数了。

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DecodeBase64

func DecodeBase64(value []byte) ([]byte, error)

func Delete

func Delete(key string) error

func EncodeBase64

func EncodeBase64(value []byte) []byte

func GetBool

func GetBool(key string) (bool, error)

func GetBytes

func GetBytes(key string) ([]byte, error)

func GetFloat

func GetFloat(key string) (float64, error)

func GetInt

func GetInt(key string) (int64, error)

func GetString

func GetString(key string) (string, error)

func GetStuct

func GetStuct(key string, ptr interface{}) error

func GetTime

func GetTime(key string) (time.Time, error)

func InitMemcacheStore

func InitMemcacheStore(addr ...string)

func InitMemoryStore

func InitMemoryStore(max_size ...uint64)

func InitRedisStore

func InitRedisStore(address string, password string)

func InitRedisStoreWithDB

func InitRedisStoreWithDB(address string, password string, db string)

func InitRedisStoreWithPool

func InitRedisStoreWithPool(pool *redis.Pool)

func Set

func Set(key string, value interface{}, max_age ...uint) error

func SetCacheStore

func SetCacheStore(store CacheStore)

Types

type CacheStore

type CacheStore interface {
	SaveData(ctx context.Context, key string, data []byte, max_age uint) error
	ReadData(ctx context.Context, key string) ([]byte, error)
	Exist(ctx context.Context, key string) (bool, error)
	Delete(ctx context.Context, key string) error
}

func GetCacheStore

func GetCacheStore() CacheStore

type CookieStore

type CookieStore struct {
	CookieName string
	HashKey    string
}

func NewCookieStore

func NewCookieStore(cookie_name string, hash_key string) *CookieStore

func (*CookieStore) Delete

func (this *CookieStore) Delete(ctx context.Context, key string) error

func (*CookieStore) Exist

func (this *CookieStore) Exist(ctx context.Context, key string) (bool, error)

func (*CookieStore) ReadData

func (this *CookieStore) ReadData(ctx context.Context, sid string) ([]byte, error)

func (*CookieStore) SaveData

func (this *CookieStore) SaveData(ctx context.Context, sid string, data []byte, max_age uint) error

type DataCache

type DataCache struct {
	// contains filtered or unexported fields
}

func NewMemoryStore

func NewMemoryStore(max_size ...uint64) *DataCache

func (*DataCache) Delete

func (mem *DataCache) Delete(ctx context.Context, key string) error

func (*DataCache) Exist

func (mem *DataCache) Exist(ctx context.Context, sid string) (bool, error)

func (*DataCache) ReadData

func (mem *DataCache) ReadData(ctx context.Context, sid string) ([]byte, error)

func (*DataCache) SaveData

func (mem *DataCache) SaveData(ctx context.Context, sid string, data []byte, max_age uint) error

type DataItem

type DataItem struct {
	// contains filtered or unexported fields
}

type StoreMemcached

type StoreMemcached struct {
	// contains filtered or unexported fields
}

func NewMemcacheStore

func NewMemcacheStore(addr ...string) *StoreMemcached

func (StoreMemcached) Delete

func (s StoreMemcached) Delete(ctx context.Context, key string) error

func (StoreMemcached) Exist

func (s StoreMemcached) Exist(ctx context.Context, key string) (bool, error)

func (*StoreMemcached) ReadData

func (s *StoreMemcached) ReadData(ctx context.Context, key string) ([]byte, error)

func (*StoreMemcached) SaveData

func (s *StoreMemcached) SaveData(ctx context.Context, key string, data []byte, max_age uint) error

type StoreRedis

type StoreRedis struct {
	// contains filtered or unexported fields
}

func NewRedisStore

func NewRedisStore(address string, password string) *StoreRedis

func NewRedisStoreWithDB

func NewRedisStoreWithDB(address string, password string, db string) *StoreRedis
type Pool struct {
    // Dial()方法返回一个连接,从在需要创建连接到的时候调用
    Dial func() (Conn, error)
    // TestOnBorrow()方法是一个可选项,该方法用来诊断一个连接的健康状态
    TestOnBorrow func(c Conn, t time.Time) error
   // 最大空闲连接数
    MaxIdle int
    // 一个pool所能分配的最大的连接数目
    // 当设置成0的时候,该pool连接数没有限制
    MaxActive int
    // 空闲连接超时时间,超过超时时间的空闲连接会被关闭。
    // 如果设置成0,空闲连接将不会被关闭
    // 应该设置一个比redis服务端超时时间更短的时间
    IdleTimeout time.Duration
}

func NewRedisStoreWithPool

func NewRedisStoreWithPool(pool *redis.Pool) *StoreRedis

func (*StoreRedis) Close

func (s *StoreRedis) Close() error

func (*StoreRedis) Delete

func (s *StoreRedis) Delete(ctx context.Context, key string) error

func (*StoreRedis) Exist

func (s *StoreRedis) Exist(ctx context.Context, key string) (bool, error)

func (*StoreRedis) ReadData

func (s *StoreRedis) ReadData(ctx context.Context, key string) ([]byte, error)

func (*StoreRedis) SaveData

func (s *StoreRedis) SaveData(ctx context.Context, key string, data []byte, max_age uint) error

SETEX 命令:设置指定 key 的值为 value,并将 key 的过期时间设为 seconds (以秒为单位) 如果 key 已经存在, SETEX 命令将会替换旧的值。

Directories

Path Synopsis
mod
memcache
Package memcache provides a client for the memcached cache server.
Package memcache provides a client for the memcached cache server.
redis
Package redis is a client for the Redis database.
Package redis is a client for the Redis database.

Jump to

Keyboard shortcuts

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