SoFunction
Updated on 2025-03-05

Examples of using two popular cache libraries in Go language

Preface

Implementing caches with expiration times in Go usually requires a cache system that can automatically handle key-value expiration. While this functionality is not directly provided in the standard library, there are several popular third-party libraries that can serve this need well. Below I will introduce two more popular Go cache libraries: go-cache and bigcache.

1. go-cache

go-cache is an in-memory key-value pair cache library that supports expired entries. It is a thread-safe cache library that sets the time to survive (TTL) of each cache item.

Install go-cache:

go get /patrickmn/go-cache

Example of usage:

package main

import (
    "fmt"
    "/patrickmn/go-cache"
    "time"
)

func main() {
    // Create a cache, set the default expiration time to 5 minutes, and clean out expired items every 10 minutes    c := (5*, 10*)

    // Set a key value, the expiration time is 1 minute    ("key1", "value1", 1*)

    // Get key value from cache    val, found := ("key1")
    if found {
        ("key1:", val)
    }

    // Wait for more than 1 minute and try to get it again    (70 * )
    val, found = ("key1")
    if found {
        ("key1 still:", val)
    } else {
        ("key1 has expired")
    }
}

In this example, we create a go-cache instance and add a key-value pair, setting an expiration time of 1 minute. Cache items can be easily added and retrieved through Set and Get methods.

2. bigcache

bigcache is an efficient key-value cache that is optimized for stand-alone environments. It does not come with an expiration process, but can be configured to enable it when set.

Install bigcache

go get /allegro/bigcache

Example of usage:

package main

import (
    "fmt"
    "/allegro/bigcache"
    "time"
)

func main() {
    config := (10 * )
     = 5 * 

    // Create a cache    cache, err := (config)
    if err != nil {
        panic(err)
    }

    // Add key value    ("key1", []byte("value1"))

    // Get key value    entry, err := ("key1")
    if err != nil {
        ("Error retrieving key1:", err)
    } else {
        ("key1:", string(entry))
    }

    // Simulate time lapse    (15 * )
    _, err = ("key1")
    if err != nil {
        ("key1 has expired")
    }
}

bigcacheIt is more suitable for handling large amounts of data and high load situations, but its configuration and use are relatively complex.

Both libraries can implement caches with expiration times in Go. Which one is chosen depends on your specific needs and application scenarios.

Summarize

This is the article about the use of two more popular cache libraries in Go. For more related Go cache library content, please search for my previous articles or continue browsing the related articles below. I hope you will support me in the future!