Go语言实现缓存接口数据

使用 go 语言和 redis 实现简单的接口缓存中间件,代码供参考:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package main

import (
"encoding/json"
"fmt"
"net/http"
"time"

"github.com/gin-gonic/gin"
"github.com/gomodule/redigo/redis"
)

// Client redis客户端连接
var Client redis.Conn

func init() {
// 建立 redis 连接
r, err := redis.Dial(
"tcp",
"127.0.0.1:6379",
redis.DialConnectTimeout(time.Minute),
redis.DialReadTimeout(5*time.Second),
redis.DialWriteTimeout(5*time.Second),
)
if err != nil {
panic(err)
}
Client = r
}

// Cache ...
func Cache(expire int) gin.HandlerFunc {
prefix := "test:"
return func(c *gin.Context) {
if c.Request.Method != "GET" {
c.Next()
return
}

key := c.Request.URL.String()

// 如果接口 header 中有 skipCache=skip,则跳过使用 redis 缓存
if skipCache := c.GetHeader("skipCache"); skipCache != "skip" {
if value, err := redis.String(Client.Do("get", prefix+key)); err == nil {
c.Header("Content-Type", "application/json")
c.String(http.StatusOK, fmt.Sprintf("%s", value))
c.Abort()
return
}
}

c.Next()

// 如果没有使用 redis 缓存,则更新缓存中的数据
if data, exists := c.Get("data"); exists {
ret, err := json.Marshal(data)
if err == nil {
Client.Do("set", prefix+key, ret, "EX", expire)
}
}
}
}

type test struct {
A string `json:"a"`
B string `json:"b"`
}

func main() {
r := gin.Default()

r.GET("/test", Cache(600), func(c *gin.Context) {
fmt.Println("skipCache")
data := []test{
{A: "x", B: "y"},
{A: "x", B: "y"},
}
c.Set("data", data)
c.JSON(http.StatusOK, data)
})

r.Run(":8888")
}
◀        
        ▶