github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/framework/cache/cache.go (about)

     1  // The package is migrated from beego, you can get from following link:
     2  // import(
     3  //   "github.com/beego/beego/v2/client/cache"
     4  // )
     5  // Copyright 2023. All Rights Reserved.
     6  //
     7  // Licensed under the Apache License, Version 2.0 (the "License");
     8  // you may not use this file except in compliance with the License.
     9  // You may obtain a copy of the License at
    10  //
    11  //      http://www.apache.org/licenses/LICENSE-2.0
    12  //
    13  // Unless required by applicable law or agreed to in writing, software
    14  // distributed under the License is distributed on an "AS IS" BASIS,
    15  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    16  // See the License for the specific language governing permissions and
    17  // limitations under the License.
    18  
    19  // Package cache provide a Cache interface and some implement engine
    20  // Usage:
    21  //
    22  // import(
    23  //
    24  //	"github.com/beego/beego/v2/client/cache"
    25  //
    26  // )
    27  //
    28  // bm, err := cache.NewCache("memory", `{"interval":60}`)
    29  //
    30  // Use it like this:
    31  //
    32  //	bm.Put("astaxie", 1, 10 * time.Second)
    33  //	bm.Get("astaxie")
    34  //	bm.IsExist("astaxie")
    35  //	bm.Delete("astaxie")
    36  package cache
    37  
    38  import (
    39  	"context"
    40  	"fmt"
    41  	"time"
    42  
    43  	"github.com/mdaxf/iac/framework/berror"
    44  )
    45  
    46  // Cache interface contains all behaviors for cache adapter.
    47  // usage:
    48  //
    49  //	cache.Register("file",cache.NewFileCache) // this operation is run in init method of file.go.
    50  //	c,err := cache.NewCache("file","{....}")
    51  //	c.Put("key",value, 3600 * time.Second)
    52  //	v := c.Get("key")
    53  //
    54  //	c.Incr("counter")  // now is 1
    55  //	c.Incr("counter")  // now is 2
    56  //	count := c.Get("counter").(int)
    57  type Cache interface {
    58  	// Get a cached value by key.
    59  	Get(ctx context.Context, key string) (interface{}, error)
    60  	// GetMulti is a batch version of Get.
    61  	GetMulti(ctx context.Context, keys []string) ([]interface{}, error)
    62  	// Put Set a cached value with key and expire time.
    63  	Put(ctx context.Context, key string, val interface{}, timeout time.Duration) error
    64  	// Delete cached value by key.
    65  	// Should not return error if key not found
    66  	Delete(ctx context.Context, key string) error
    67  	// Incr Increment a cached int value by key, as a counter.
    68  	Incr(ctx context.Context, key string) error
    69  	// Decr Decrement a cached int value by key, as a counter.
    70  	Decr(ctx context.Context, key string) error
    71  	// IsExist Check if a cached value exists or not.
    72  	// if key is expired, return (false, nil)
    73  	IsExist(ctx context.Context, key string) (bool, error)
    74  	// ClearAll Clear all cache.
    75  	ClearAll(ctx context.Context) error
    76  	// StartAndGC Start gc routine based on config string settings.
    77  	StartAndGC(config string) error
    78  }
    79  
    80  // Instance is a function create a new Cache Instance
    81  type Instance func() Cache
    82  
    83  var adapters = make(map[string]Instance)
    84  
    85  // Register makes a cache adapter available by the adapter name.
    86  // If Register is called twice with the same name or if driver is nil,
    87  // it panics.
    88  func Register(name string, adapter Instance) {
    89  	fmt.Println("Register:", name, adapter)
    90  	if adapter == nil {
    91  		panic(berror.Error(NilCacheAdapter, "cache: Register adapter is nil").Error())
    92  	}
    93  	if _, ok := adapters[name]; ok {
    94  		panic("cache: Register called twice for adapter " + name)
    95  	}
    96  	adapters[name] = adapter
    97  }
    98  
    99  // NewCache creates a new cache driver by adapter name and config string.
   100  // config: must be in JSON format such as {"interval":360}.
   101  // Starts gc automatically.
   102  func NewCache(adapterName, config string) (adapter Cache, err error) {
   103  	instanceFunc, ok := adapters[adapterName]
   104  	if !ok {
   105  
   106  		fmt.Println("err:", err)
   107  		err = berror.Errorf(UnknownAdapter, "cache: unknown adapter name %s (forgot to import?)", adapterName)
   108  		panic(err.Error())
   109  		//}
   110  
   111  	}
   112  
   113  	adapter = instanceFunc()
   114  	fmt.Println("adapter:", adapter)
   115  	err = adapter.StartAndGC(config)
   116  	if err != nil {
   117  		adapter = nil
   118  	}
   119  	return
   120  }