Giter Club home page Giter Club logo

gookit / cache Goto Github PK

View Code? Open in Web Editor NEW
193.0 5.0 19.0 373 KB

🗃 Generic cache use and cache manage. Provide a unified usage API by packaging various commonly used drivers. Support File, Memory, Redis, Memcached and more. Go 通用的缓存使用库,通过包装各种常用的驱动,来提供统一的使用API,便于使用。

Home Page: https://pkg.go.dev/github.com/gookit/cache

License: MIT License

Go 100.00%
file-cache redis-cache memory-cache memcached-cache buntdb cache-manager custom-driver cache golang redis

cache's Introduction

Cache

GitHub go.mod Go version GoDoc Go Report Card Actions Status

中文说明

Generic cache use and cache manager for golang.

Provide a unified usage API by packaging various commonly used drivers.

All cache driver implemented the cache.Cache interface. So, You can add any custom driver.

Packaged Drivers:

Internal:

Notice: The built-in implementation is relatively simple and is not recommended for production environments; the production environment recommends using the third-party drivers listed above.

GoDoc

Install

The package supports 3 last Go versions and requires a Go version with modules support.

go get github.com/gookit/cache

Cache Interface

All cache driver implemented the cache.Cache interface. So, You can add any custom driver.

type Cache interface {
	// basic operation
	Has(key string) bool
	Get(key string) any
	Set(key string, val any, ttl time.Duration) (err error)
	Del(key string) error
	// multi operation
	GetMulti(keys []string) map[string]any
	SetMulti(values map[string]any, ttl time.Duration) (err error)
	DelMulti(keys []string) error
	// clear and close
	Clear() error
	Close() error
}

Usage

package main

import (
	"fmt"

	"github.com/gookit/cache"
	"github.com/gookit/cache/gcache"
	"github.com/gookit/cache/gocache"
	"github.com/gookit/cache/goredis"
	"github.com/gookit/cache/redis"
)

func main() {
	// register one(or some) cache driver
	cache.Register(cache.DvrFile, cache.NewFileCache(""))
	// cache.Register(cache.DvrMemory, cache.NewMemoryCache())
	cache.Register(gcache.Name, gcache.New(1000))
	cache.Register(gocache.Name, gocache.NewGoCache(cache.OneDay, cache.FiveMinutes))
	cache.Register(redis.Name, redis.Connect("127.0.0.1:6379", "", 0))
	cache.Register(goredis.Name, goredis.Connect("127.0.0.1:6379", "", 0))

	// setting default driver name
	cache.DefaultUse(gocache.Name)

	// quick use.(it is default driver)
	//
	// set
	cache.Set("name", "cache value", cache.TwoMinutes)
	// get
	val := cache.Get("name")
	// del
	cache.Del("name")

	// get: "cache value"
	fmt.Print(val)

	// More ...
	// fc := cache.Driver(gcache.Name)
	// fc.Set("key", "value", 10)
	// fc.Get("key")
}

With Options

gords := goredis.Connect("127.0.0.1:6379", "", 0)
gords.WithOptions(cache.WithPrefix("cache_"), cache.WithEncode(true))

cache.Register(goredis.Name, gords)

// set
// real key is: "cache_name"
cache.Set("name", "cache value", cache.TwoMinutes)

// get: "cache value"
val := cache.Get("name")

Gookit packages

  • gookit/ini Go config management, use INI files
  • gookit/rux Simple and fast request router for golang HTTP
  • gookit/gcli build CLI application, tool library, running CLI commands
  • gookit/slog Lightweight, extensible, configurable logging library written in Go
  • gookit/event Lightweight event manager and dispatcher implements by Go
  • gookit/cache Provide a unified usage API by packaging various commonly used drivers.
  • gookit/config Go config management. support JSON, YAML, TOML, INI, HCL, ENV and Flags
  • gookit/color A command-line color library with true color support, universal API methods and Windows support
  • gookit/filter Provide filtering, sanitizing, and conversion of golang data
  • gookit/validate Use for data validation and filtering. support Map, Struct, Form data
  • gookit/goutil Some utils for the Go: string, array/slice, map, format, cli, env, filesystem, test and more
  • More, please see https://github.com/gookit

License

MIT

cache's People

Contributors

dependabot[bot] avatar iaping avatar inhere avatar lemos1235 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

cache's Issues

Potential import collision: import path should be "go.etcd.io/bbolt", not "github.com/etcd-io/bbolt"

Background

I find that go.etcd.io/bbolt and github.com/etcd-io/bbolt coexist in this repo:
https://github.com/gookit/cache/blob/master/go.mod (Line 9 & 14)

github.com/etcd-io/bbolt v1.3.3
go.etcd.io/bbolt v1.3.3 // indirect

That’s because the etcd-io/bbolt has already renamed it’s import path from "github.com/etcd-io/bbolt" to "go.etcd.io/bbolt". When you use the old path "github.com/etcd-io/bbolt" to import the bbolt, will reintroduces etcd-io/bbolt through the import statements "import go.etcd.io/bbolt" in the go source file of etcd-io/bbolt.

https://github.com/etcd-io/bbolt/blob/v1.3.3/cursor_test.go#L14

package bbolt_test
import (
	bolt "go.etcd.io/bbolt"
	…
) 

The "go.etcd.io/bbolt" and "github.com/etcd-io/bbolt" are the same repos. This will work in isolation, bring about potential risks and problems.

Solution

Follow the requirements of [etcd-io/bbolt README.md]https://github.com/etcd-io/bbolt/blob/v1.3.3/README.md:

To start using Bolt, install Go and run go get:
>$ go get go.etcd.io/bbolt/...
This will retrieve the library and install the bolt command line utility into your $GOBIN path.

Importing bbolt
To use bbolt as an embedded key-value store, import as:
>import bolt "go.etcd.io/bbolt"
…

Replace all the old import paths, change "github.com/etcd-io/bbolt" to "go.etcd.io/bbolt ".
Where did you import it: https://github.com/gookit/cache/search?q=github.com%2Fetcd-io%2Fbbolt&unscoped_q=github.com%2Fetcd-io%2Fbbolt

更新下go.mod 的redigo 版本

由于redigo的版本号写错,老版本的是v2.0.0,最新版的反而是v1.8.8。
而最新版的go 1.17+ 使用go mod tidy会检查模块依赖的版本,复制到顶层的go.mod。
而版本错误的原因导致每次go mod tidy都会更新错版本,导致顶层项目用了错误的老版本的v2
所以请将go.mod中的redigo版本换一下
github.com/gomodule/redigo v2.0.0+incompatible
改成
github.com/gomodule/redigo v1.8.8
也可以顺便加一句exclude github.com/gomodule/redigo v2.0.0+incompatible

panic: interface conversion

I got panic when try to get cache value with multiple runs.

panic: interface conversion: interface {} is []interface {}, not main.Users

Code to reproduce. Try this code 2 times.

package main

import (
	"fmt"
	"os"
	"path/filepath"
	"time"

	"github.com/gookit/cache"
)

type User struct {
	Name string
}

type Users []*User

const key = "user1"

func main() {
	if cache.Has(key) {
		u, ok := cache.Get("user1").(Users)
		if !ok {
			panic("can not assert cache data")
		}
		fmt.Printf("%#v\n", u[0])
	}
	u := Users{&User{Name: "TestUser"}}
	cache.Set(key, u, 1*time.Hour)
	if cache.Has(key) {
		fmt.Println("cache written")
		u2, ok := cache.Get("user1").(Users)
		if !ok || u[0] != u2[0] {
			fmt.Println("cache data is not OK")
		} else {
			fmt.Println("cache is ok")
		}
	}
}

func init() {
	cache.Register(cache.DvrFile, cache.NewFileCache(filepath.Join(os.TempDir(), "tcache-dir")))
}

First time:

cache written
cache is ok

Second time:

panic: can not assert cache data

goroutine 1 [running]:
main.main()
        /run/media/unikum/UNIKUM-STORAGE/private/prog/go/tcache/main.go:24 +0x28a
exit status 2

请问 cache 是否有定期清理过期的内容?

Hi,

感谢提供 cache 包。:)

粗略过了几个源码代码,file/memory cache 似乎没有定期清理过期的内容,而是只在 Get() 的时候检查命中的内容是否过期。
假如用 Set() 添加了内容并设置了过期时间,但是之后使用过程中从未命中,那它会在过期时间到了之后被(主动)清理掉吗?

lru size没传入

func New(size int) *GCache {
	return &GCache{
		db: gcache.New(20).LRU().Build(),
	}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.