This repository has been archived by the owner on Mar 21, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmysql.go
179 lines (150 loc) · 4.23 KB
/
mysql.go
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
// Copyright 2014 The Macaron Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
package cache
import (
"crypto/md5"
"database/sql"
"encoding/hex"
"log"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/go-macaron/cache"
)
// MysqlCacher represents a mysql cache adapter implementation.
type MysqlCacher struct {
c *sql.DB
interval int
}
// NewMysqlCacher creates and returns a new mysql cacher.
func NewMysqlCacher() *MysqlCacher {
return &MysqlCacher{}
}
func (c *MysqlCacher) md5(key string) string {
m := md5.Sum([]byte(key))
return hex.EncodeToString(m[:])
}
// Put puts value into cache with key and expire time.
// If expired is 0, it will be deleted by next GC operation.
func (c *MysqlCacher) Put(key string, val interface{}, expire int64) error {
item := &cache.Item{Val: val}
data, err := cache.EncodeGob(item)
if err != nil {
return err
}
now := time.Now().Unix()
if c.IsExist(key) {
_, err = c.c.Exec("UPDATE cache SET data=?, created=?, expire=? WHERE `key`=?", data, now, expire, c.md5(key))
} else {
_, err = c.c.Exec("INSERT INTO cache(`key`,data,created,expire) VALUES(?,?,?,?)", c.md5(key), data, now, expire)
}
return err
}
func (c *MysqlCacher) read(key string) (*cache.Item, error) {
var (
data []byte
created int64
expire int64
)
err := c.c.QueryRow("SELECT data,created,expire FROM cache WHERE `key`=?", c.md5(key)).Scan(&data, &created, &expire)
if err != nil {
return nil, err
}
item := new(cache.Item)
if err = cache.DecodeGob(data, item); err != nil {
return nil, err
}
item.Created = created
item.Expire = expire
return item, nil
}
// Get gets cached value by given key.
func (c *MysqlCacher) Get(key string) interface{} {
item, err := c.read(key)
if err != nil {
return nil
}
if item.Expire > 0 &&
(time.Now().Unix()-item.Created) >= item.Expire {
c.Delete(key)
return nil
}
return item.Val
}
// Delete deletes cached value by given key.
func (c *MysqlCacher) Delete(key string) error {
_, err := c.c.Exec("DELETE FROM cache WHERE `key`=?", c.md5(key))
return err
}
// Incr increases cached int-type value by given key as a counter.
func (c *MysqlCacher) Incr(key string) error {
item, err := c.read(key)
if err != nil {
return err
}
item.Val, err = cache.Incr(item.Val)
if err != nil {
return err
}
return c.Put(key, item.Val, item.Expire)
}
// Decrease cached int value.
func (c *MysqlCacher) Decr(key string) error {
item, err := c.read(key)
if err != nil {
return err
}
item.Val, err = cache.Decr(item.Val)
if err != nil {
return err
}
return c.Put(key, item.Val, item.Expire)
}
// IsExist returns true if cached value exists.
func (c *MysqlCacher) IsExist(key string) bool {
var data []byte
err := c.c.QueryRow("SELECT data FROM cache WHERE `key`=?", c.md5(key)).Scan(&data)
if err != nil && err != sql.ErrNoRows {
panic("cache/mysql: error checking existence: " + err.Error())
}
return err != sql.ErrNoRows
}
// Flush deletes all cached data.
func (c *MysqlCacher) Flush() error {
_, err := c.c.Exec("DELETE FROM cache")
return err
}
func (c *MysqlCacher) startGC() {
if c.interval < 1 {
return
}
if _, err := c.c.Exec("DELETE FROM cache WHERE UNIX_TIMESTAMP(NOW()) - created >= expire"); err != nil {
log.Printf("cache/mysql: error garbage collecting: %v", err)
}
time.AfterFunc(time.Duration(c.interval)*time.Second, func() { c.startGC() })
}
// StartAndGC starts GC routine based on config string settings.
func (c *MysqlCacher) StartAndGC(opt cache.Options) (err error) {
c.interval = opt.Interval
c.c, err = sql.Open("mysql", opt.AdapterConfig)
if err != nil {
return err
} else if err = c.c.Ping(); err != nil {
return err
}
go c.startGC()
return nil
}
func init() {
cache.Register("mysql", NewMysqlCacher())
}