How to write data to cache using Golang?

WBOY
Release: 2024-06-01 13:21:57
Original
1117 people have browsed it

Abstract: There are many methods for caching operations using the Go language, including: sync.Map: Built-in concurrency-safe mapping, suitable for small-scale caching. go-cache: A third-party library that provides more advanced features such as eviction, expiration, and timeouts. In practical applications, go-cache can be used to cache database query results, thereby improving application performance and reducing database query operations.

如何使用 Golang 将数据写入缓存?

Use Golang to write data to cache

In distributed systems, caching is a crucial technology. It can significantly improve application performance. The Golang language provides a wide range of libraries to use caching, including the built-in sync.Map type and third-party libraries such as github.com/patrickmn/go-cache.

Use sync.Map

sync.Map is a concurrency-safe mapping provided in the Golang standard library. It can be used to store key-value pairs and can be accessed from multiple goroutines at the same time. To store data using sync.Map, follow these steps:

package main

import (
    "sync"
)

var cache = sync.Map{}

func main() {
    // 将 "key1" 映射到值 "value1"
    cache.Store("key1", "value1")

    // 检索映射到 "key1" 的值
    value, ok := cache.Load("key1")
    if !ok {
        // 如果键不存在,则返回 nil
        fmt.Println("Key not found")
        return
    }

    fmt.Println(value) // 输出:"value1"
}
Copy after login

Using go-cache

go-cache is a more feature-rich caching library that provides advanced features such as eviction, expiration, and timeouts. To use go-cache to store data, please follow these steps:

package main

import (
    "github.com/patrickmn/go-cache"
    "time"
)

var cache = cache.New(5*time.Minute, 10*time.Minute)

func main() {
    // 将 "key1" 映射到值 "value1",并设置 5 分钟的超时
    cache.Set("key1", "value1", 5*time.Minute)

    // 检索映射到 "key1" 的值
    value, found := cache.Get("key1")
    if !found {
        // 如果键不存在,则返回 nil
        fmt.Println("Key not found")
        return
    }

    fmt.Println(value) // 输出:"value1"
}
Copy after login

Practical Case

The following is an example of using go-cache Example of caching database query results in a web application:

package main

import (
    "database/sql"
    "fmt"
    "github.com/patrickmn/go-cache"
    "time"
)

var (
    db     *sql.DB
    cache  = cache.New(5*time.Minute, 10*time.Minute)
)

func main() {
    // 打开数据库连接
    db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/database")
    if err != nil {
        panic(err)
    }

    // 检索用户数据并缓存
    rows, err := db.Query("SELECT * FROM users")
    if err != nil {
        panic(err)
    }

    for rows.Next() {
        var id int
        var name string
        if err := rows.Scan(&id, &name); err != nil {
            panic(err)
        }

        cache.Set(fmt.Sprintf("user:%d", id), name, cache.NoExpiration)
    }

    // 从缓存中检索用户姓名
    name, found := cache.Get("user:1")
    if found {
        fmt.Println(name) // 输出:John Doe
    } else {
        fmt.Println("Key not found")
    }
}
Copy after login

By leveraging Golang's caching capabilities, you can significantly improve the performance of your application and reduce queries to the underlying database.

The above is the detailed content of How to write data to cache using Golang?. 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