예제 #1
0
// SetExpire sets data with TTL.
func (c *CacheTTL) SetExpire(key string, data interface{}, ttl int64) error {
	if key == "" {
		return nil
	}

	c.itemsMu.Lock()
	defer c.itemsMu.Unlock()

	if data == nil {
		delete(c.items, key)
		return nil
	}

	// return oldest item when the cache reaches maximum size
	if len(c.deleteQueue) >= c.maxSize {
		c.deleteOldest()
	}

	item := eurekache.NewItem()
	item.SetExpire(ttl)
	item.Value = data
	c.items[key] = item
	c.deleteQueue = append(c.deleteQueue, key)
	return nil
}
예제 #2
0
// SetExpire sets data into redis with TTL. data is wrapped by gob-encoded Item
func (c *RedisCache) SetExpire(key string, data interface{}, ttl int64) error {
	conn, err := c.conn()
	if err != nil {
		return err
	}
	defer conn.Close()

	if data == nil {
		_, err = conn.Do("DEL", c.prefix+key)
		return err
	}

	item := eurekache.NewItem()
	item.SetExpire(ttl)
	item.Value = data

	var buf bytes.Buffer
	enc := gob.NewEncoder(&buf)
	err = enc.Encode(item)
	if err != nil {
		return err
	}

	switch {
	case ttl < 1:
		_, err = conn.Do("SET", c.prefix+key, buf.Bytes())
	default:
		ttl = ttl / 1000 // convert milli-sec to sec
		_, err = conn.Do("SETEX", c.prefix+key, ttl, buf.Bytes())
	}

	if err != nil {
		return err
	}
	return nil
}