无法从缓存中获得结果。只工作请求基地。我需要优化应用程序的许多请求。这是我第一个用歌朗的应用,请原谅我。如何获得缓存结果?
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()
}
}这:所有“isProxy”返回0,1,-1值。
发布于 2022-01-17 20:45:07
创建一个全局变量并将缓存存储在那里。示例:
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在内部创建锁。谢谢你纠正我。
https://stackoverflow.com/questions/70745556
复制相似问题