123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 |
- package cache
- import (
- "fmt"
- "gopkg.in/macaron.v1"
- )
- const _VERSION = "0.3.0"
- func Version() string {
- return _VERSION
- }
- type Cache interface {
-
- Put(key string, val interface{}, timeout int64) error
-
- Get(key string) interface{}
-
- Delete(key string) error
-
- Incr(key string) error
-
- Decr(key string) error
-
- IsExist(key string) bool
-
- Flush() error
-
- StartAndGC(opt Options) error
- }
- type Options struct {
-
- Adapter string
-
- AdapterConfig string
-
- Interval int
-
- OccupyMode bool
-
- Section string
- }
- func prepareOptions(options []Options) Options {
- var opt Options
- if len(options) > 0 {
- opt = options[0]
- }
- if len(opt.Section) == 0 {
- opt.Section = "cache"
- }
- sec := macaron.Config().Section(opt.Section)
- if len(opt.Adapter) == 0 {
- opt.Adapter = sec.Key("ADAPTER").MustString("memory")
- }
- if opt.Interval == 0 {
- opt.Interval = sec.Key("INTERVAL").MustInt(60)
- }
- if len(opt.AdapterConfig) == 0 {
- opt.AdapterConfig = sec.Key("ADAPTER_CONFIG").MustString("data/caches")
- }
- return opt
- }
- func NewCacher(name string, opt Options) (Cache, error) {
- adapter, ok := adapters[name]
- if !ok {
- return nil, fmt.Errorf("cache: unknown adapter '%s'(forgot to import?)", name)
- }
- return adapter, adapter.StartAndGC(opt)
- }
- func Cacher(options ...Options) macaron.Handler {
- opt := prepareOptions(options)
- cache, err := NewCacher(opt.Adapter, opt)
- if err != nil {
- panic(err)
- }
- return func(ctx *macaron.Context) {
- ctx.Map(cache)
- }
- }
- var adapters = make(map[string]Cache)
- func Register(name string, adapter Cache) {
- if adapter == nil {
- panic("cache: cannot register adapter with nil value")
- }
- if _, dup := adapters[name]; dup {
- panic(fmt.Errorf("cache: cannot register adapter '%s' twice", name))
- }
- adapters[name] = adapter
- }
|