Exemplo n.º 1
0
// Retrieve a cache item from the cache.
func (fs *Fs) Get(key string, items ...kit.CacheItem) (kit.CacheItem, apperror.Error) {
	var item kit.CacheItem = &StrItem{}
	if items != nil {
		if len(items) != 1 {
			return nil, &apperror.Err{
				Code:    "invalid_item",
				Message: "You must specify one item only",
			}
		}
		item = items[0]
	}

	key = fs.key(key)
	if key == "" {
		return nil, apperror.New("empty_key")
	}

	exists, err := utils.FileExists(fs.keyPath(key))
	if err != nil {
		return nil, err
	}

	if !exists {
		return nil, nil
	}

	metaContent, err := utils.ReadFile(fs.keyMetaPath(key))
	if err != nil {
		return nil, err
	}
	if err := json.Unmarshal(metaContent, &item); err != nil {
		return nil, apperror.Wrap(err, "metadata_unmarshal_error")
	}

	// Reset ExpiresAt if it is zero, since json.Unmarshal produces
	// a time.Time which is not exactly equal to the zero value.
	if item.GetExpiresAt().IsZero() {
		item.SetExpiresAt(time.Time{})
	}

	content, err := utils.ReadFile(fs.keyPath(key))
	if err != nil {
		return nil, err
	}

	if err := item.FromString(string(content)); err != nil {
		return nil, apperror.Wrap(err, "cacheitem_fromstring_error")
	}

	// Return nil if item is expired.
	if item.IsExpired() {
		return nil, nil
	}

	return item, nil
}
Exemplo n.º 2
0
// Save a new item into the cache.
func (r *Redis) Set(item kit.CacheItem) Error {
	key := item.GetKey()
	if key == "" {
		return kit.AppError{Code: "empty_key"}
	}
	key = r.key(key)

	if item.IsExpired() {
		return kit.AppError{Code: "item_expired"}
	}

	expireSeconds := 0
	if expires := item.GetExpiresAt(); !expires.IsZero() {
		seconds := expires.Sub(time.Now()).Seconds()
		if seconds > 0 && seconds < 1 {
			return kit.AppError{Code: "item_expired"}
		}
		expireSeconds = int(seconds)
	}

	conn := r.pool.Get()
	defer conn.Close()

	value, err := item.ToString()
	if err != nil {
		return kit.AppError{
			Code:    "cacheitem_tostring_error",
			Message: err.Error(),
			Errors:  []error{err},
		}
	}
	if value == "" {
		return kit.AppError{Code: "empty_value"}
	}

	conn.Send("SET", key, value)
	if expireSeconds > 0 {
		conn.Send("EXPIRE", key, expireSeconds)
	}

	if tags := item.GetTags(); tags != nil {
		tagKey := r.tagKey(key)
		conn.Send("SET", tagKey, strings.Join(tags, ";"))
		if expireSeconds > 0 {
			conn.Send("EXPIRE", tagKey, expireSeconds)
		}
	}

	if err := conn.Flush(); err != nil {
		return redisErr(err)
	}

	return nil
}