Home > Backend Development > Golang > Is golang-cache global?

Is golang-cache global?

(*-*)浩
Release: 2019-12-13 11:37:51
Original
3818 people have browsed it

Is golang-cache global?

#go-cache is a memory-based, high-speed caching tool that stores k-v format. It is suitable for applications running on a single machine, can store values ​​of any data type, and can be safely used by multiple goroutines.                                                                                                                               (Recommended learning: go)

Although go-cache is not intended to be used as a persistent data store, the entire cache data can be saved to a file (or any io.Reader/Writer ), and can quickly load the specified data source from it and quickly restore the state.

Demo

package main

import (
        "log"
        "time"

        "github.com/patrickmn/go-cache"
)


func main(){

        c := cache.New(30*time.Second, 10*time.Second)


        c.Set("Title", "Spring Festival", cache.DefaultExpiration)


        value, found := c.Get("Title")
        if found {
                log.Println("found:", value)
        } else {
                log.Println("not found")
        }


        time.Sleep(60*time.Second)
        log.Println("sleep 60s...")
        value, found = c.Get("Title")
        if found {
                log.Println("found:", value)
        } else {
                log.Println("not found")
        }

}
Copy after login

output

2019/02/05 17:49:32 found: Spring Festival
2019/02/05 17:50:32 sleep 60s…
2019/02/05 17:50:32 not found
Copy after login

First, create a new cache with the key expiration time of 30s. And clear expired keys in the cache every 10 seconds.

Regular clearing of expired keys in the cache is achieved through a resident goroutine.

Next, set a key/value and its expiration time. The expiration time uses the default expiration time, which is 30s.

Get this key, you can see that this key exists in the cache at this time.

Sleep for 60s to expire the key just set.

Get this key again. At this time, the key has expired, been cleared, and is no longer in the cache

The above is the detailed content of Is golang-cache global?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template