github.com/qxnw/lib4go@v0.0.0-20180426074627-c80c7e84b925/cache/cache.go (about)

     1  package cache
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  )
     7  
     8  type ICache interface {
     9  	Get(key string) (string, error)
    10  	Decrement(key string, delta int64) (n int64, err error)
    11  	Increment(key string, delta int64) (n int64, err error)
    12  	Gets(key ...string) (r []string, err error)
    13  	Add(key string, value string, expiresAt int) error
    14  	Set(key string, value string, expiresAt int) error
    15  	Delete(key string) error
    16  	Exists(key string) bool
    17  	Delay(key string, expiresAt int) error
    18  	Close() error
    19  }
    20  
    21  //CacheResover 定义配置文件转换方法
    22  type CacheResover interface {
    23  	Resolve(address []string, conf string) (ICache, error)
    24  }
    25  
    26  var cacheResolvers = make(map[string]CacheResover)
    27  
    28  //Register 注册配置文件适配器
    29  func Register(proto string, resolver CacheResover) {
    30  	if resolver == nil {
    31  		panic("mq: Register adapter is nil")
    32  	}
    33  	if _, ok := cacheResolvers[proto]; ok {
    34  		panic("mq: Register called twice for adapter " + proto)
    35  	}
    36  	cacheResolvers[proto] = resolver
    37  }
    38  
    39  //NewCache 根据适配器名称及参数返回配置处理器
    40  func NewCache(address string, conf string) (ICache, error) {
    41  	proto, addrs, err := getNames(address)
    42  	if err != nil {
    43  		return nil, err
    44  	}
    45  	resolver, ok := cacheResolvers[proto]
    46  	if !ok {
    47  		return nil, fmt.Errorf("mq: unknown adapter name %q (forgotten import?)", proto)
    48  	}
    49  	return resolver.Resolve(addrs, conf)
    50  }
    51  
    52  func getNames(address string) (proto string, raddr []string, err error) {
    53  	addr := strings.SplitN(address, "://", 2)
    54  	if len(addr) != 2 {
    55  		return "", nil, fmt.Errorf("cache地址配置错误%s,格式:memcached://192.168.0.1:11211", addr)
    56  	}
    57  	if len(addr[0]) == 0 {
    58  		return "", nil, fmt.Errorf("cache地址配置错误%s,格式:memcached://192.168.0.1:11211", addr)
    59  	}
    60  	if len(addr[1]) == 0 {
    61  		return "", nil, fmt.Errorf("cache地址配置错误%s,格式:memcached://192.168.0.1:11211", addr)
    62  	}
    63  	proto = addr[0]
    64  	raddr = strings.Split(addr[1], ",")
    65  	return
    66  }