Exemple #1
0
// Set sets the value of an item, regardless of wether or not the value is
// already cached.
//
// ttl defines the number of seconds the value should be cached. If ttl is 0,
// the item will be cached infinitely. If ttl is < 0, the value will be deleted
// from the cache using the `Delete()` function.
func (c *Cache) Set(key string, value []byte, ttl int64) error {
	expiry := time.Now().Add(time.Duration(ttl) * time.Second)

	var expire bool
	if ttl < 0 {
		return c.Delete(key)
	} else if ttl != 0 {
		expire = true
	}

	c.items[key] = &cachedItem{value, expiry, expire, encoding.Md5Sum(value)}
	c.keys = append(c.keys, key)
	c.size += uintptr(len(value)) // TODO: if already exists, don't add this all
	c.lru(key)
	c.evict()
	return nil
}
Exemple #2
0
// Get gets the value out of the map associated with the provided key.
func (c *Cache) Get(key string) ([]byte, string, error) {
	value, err := c.client.Do("GET", key)

	if err != nil {
		return []byte{}, "", err
	}

	if value == nil {
		return []byte{}, "", errors.NewNotFound(key)
	}

	val, ok := value.([]byte)

	if !ok {
		return nil, "", errors.NewInvalidData(key)
	}

	return val, encoding.Md5Sum(val), nil
}
Exemple #3
0
// GetMulti gets multiple values from the cache and returns them as a map. It
// uses `Get` internally to retrieve the data.
func (c *Cache) GetMulti(keys []string) (map[string][]byte, map[string]string, map[string]error) {
	cValues, err := c.client.Do("MGET", keyArgs(keys)...)
	items := make(map[string][]byte)
	errs := make(map[string]error)
	tokens := make(map[string]string)

	for _, v := range keys {
		errs[v] = errors.NewNotFound(v)
	}

	if err == nil {
		values := cValues.([]interface{})
		for i, val := range values {
			byteVal, ok := val.([]byte)
			if ok {
				items[keys[i]] = byteVal
				tokens[keys[i]] = encoding.Md5Sum(items[keys[i]])
				errs[keys[i]] = nil
			}
		}
	}

	return items, tokens, errs
}