Exemplo n.º 1
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
}