登录
首页 >  Golang >  Go问答

使用Golang中net/http库处理和缓存结果

来源:stackoverflow

时间:2024-03-19 21:00:33 187浏览 收藏

在使用 Go 语言中的 `net/http` 库处理大量请求时,为了优化应用程序的性能,可以使用缓存来存储结果。通过将请求结果缓存起来,可以避免重复执行昂贵的数据库查询或其他耗时的操作,从而显著提高响应速度。本文将介绍如何使用 `github.com/patrickmn/go-cache` 库来实现缓存,包括如何创建缓存、存储结果以及从缓存中检索结果。通过使用缓存,可以有效地减少应用程序的响应时间,并提升整体性能。

问题内容

无法从缓存中获取结果。仅向基地提出工作要求。我需要针对许多请求优化应用程序。这是我第一个使用 golang 的应用程序,请宽容。如何获取缓存结果?

import (
    "fmt"
    "log"
    "net/http"
    "time"

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

func main() {
    http.HandleFunc("/", HelloHandler)
    http.ListenAndServe(":8080", nil)
    log.Fatal(http.ListenAndServe(":8080", nil))
}
func HelloHandler(w http.ResponseWriter, r *http.Request) {
    c := cache.New(5*time.Minute, 10*time.Minute)
    ip := r.URL.Query().Get("ip")
    x, found := c.Get(ip)
    if found {
        if x != "0" {
            w.WriteHeader(http.StatusOK)
            fmt.Fprintf(w, "isProxy Cache")
        } else {
            w.WriteHeader(http.StatusNoContent)
            fmt.Fprintf(w, "notProxy Cache")
        }

    } else {
        db, err := ip2proxy.OpenDB("./IP2PROXY-IP-PROXYTYPE-COUNTRY.BIN")
        if err != nil {
            return
        }
        all, err := db.GetAll(ip)
        if err != nil {
            fmt.Print(err)
            return
        }
        isProxy := all["isProxy"]
        c.Set(ip, isProxy, cache.DefaultExpiration)
        if isProxy != "0" {
            w.WriteHeader(http.StatusOK)
            fmt.Fprintf(w, "isProxy ")
        } else {
            w.WriteHeader(http.StatusNoContent)
            fmt.Fprintf(w, "notProxy ")
        }
        db.Close()
    }
}

此:all["isproxy"] 返回 0、1、-1 值


正确答案


创建一个全局变量并将缓存存储在那里。示例:

var globalCache *cache.Cache

func main() {
    globalCache = cache.New(5*time.Minute, 10*time.Minute)

    http.HandleFunc("/", HelloHandler)
    http.ListenAndServe(":8080", nil)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

func HelloHandler(w http.ResponseWriter, r *http.Request) {
    // use globalCache
}

更新:不需要原子性,因为cache.cache在内部进行锁定。谢谢你纠正我。

以上就是《使用Golang中net/http库处理和缓存结果》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>