Esempio n. 1
0
func main() {
	// creates a cache that can hold 10 values
	cache, _ := multicache.NewDefaultMulticache(10)

	// Nothing yet in cache
	value, ok := cache.Get("foo")
	fmt.Printf("%v %v\n", value, ok) // <nil> false

	// Add a key value pair
	cache.Add("foo", 42)
	value, ok = cache.Get("foo")
	fmt.Printf("%v %v\n", value, ok) // 42 true

	// Add a multiple key-value pair, note that the value goes first.
	cache.AddMany(44.009, "bar", "baz")
	value, ok = cache.Get("bar")
	fmt.Printf("%v %v\n", value, ok) // 44.009 true

	// Delete one key and all of the "multikeys" get removed
	cache.Remove("baz")
	value, ok = cache.Get("bar")
	fmt.Printf("%v %v\n", value, ok) // <nil> false

	// Create a multicache with your desired replacement algorithm
	// (you can even make your own)
	multicache.NewMulticache(10, &multicache.SecondChance{})

	// We even have time expiring caches, items expire after the given number
	// of ms. (10 items, 1000ms)
	multicache.CreateTimeExpireMulticache(10, 1000)
}
Esempio n. 2
0
func main() {
	// creates a cache that can hold 10 values
	cache, _ := multicache.NewDefaultMulticache(10)

	// session id and it's user
	cache.Add("1", "trillian")
	cache.Add("2", "zaphod")
	cache.Add("3", "trillian")
	cache.Add("4", "trillian")
	cache.Add("5", "ford_prefect")

	// Removes many items from the cache using a specified function that looks
	// at each item.
	// For example, if a user wants to log out of all sessions
	cache.RemoveManyFunc(func(item interface{}) bool {
		val, ok := item.(string)
		if !ok {
			return false
		}

		// true means remove the item, false means keep it.
		return val == "trillian"
	})

	// trillian is logged out
	val, ok := cache.Get("1")
	fmt.Printf("%v %v\n", val, ok) // <nil> false
	val, ok = cache.Get("3")
	fmt.Printf("%v %v\n", val, ok) // <nil> false

	// zaphod is still logged in
	val, ok = cache.Get("2")
	fmt.Printf("%v %v\n", val, ok) // zaphod true
}
Esempio n. 3
0
func main() {
	// creates a cache that can hold 10 values
	cache, _ := multicache.NewDefaultMulticache(10)

	// GetOrFind returns the item if it's in the cache or calls the given
	// function to "find" it, good if you use caching a lot and don't want to
	// keep using the if ! ok { fill_the_cache(); handle_error()}
	item, err := cache.GetOrFind("myKey", myMissFunction)

	fmt.Printf("%v, %v\n", item, err) // myKey's value, <nil>

}