forked from appleboy/gorush
-
Notifications
You must be signed in to change notification settings - Fork 0
/
boltdb.go
73 lines (61 loc) · 1.39 KB
/
boltdb.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
package boltdb
import (
"log"
"sync"
"github.com/asdine/storm/v3"
"github.com/tolki-app/gorush/config"
)
// New func implements the storage interface for gorush (https://github.com/tolki-app/gorush)
func New(config *config.ConfYaml) *Storage {
return &Storage{
config: config,
}
}
// Storage is interface structure
type Storage struct {
config *config.ConfYaml
db *storm.DB
lock sync.RWMutex
}
func (s *Storage) Add(key string, count int64) {
s.lock.Lock()
defer s.lock.Unlock()
s.setBoltDB(key, s.getBoltDB(key)+count)
}
func (s *Storage) Set(key string, count int64) {
s.lock.Lock()
defer s.lock.Unlock()
s.setBoltDB(key, count)
}
func (s *Storage) Get(key string) int64 {
s.lock.RLock()
defer s.lock.RUnlock()
return s.getBoltDB(key)
}
// Init client storage.
func (s *Storage) Init() error {
var err error
s.db, err = storm.Open(s.config.Stat.BoltDB.Path)
return err
}
// Close the storage connection
func (s *Storage) Close() error {
if s.db == nil {
return nil
}
return s.db.Close()
}
func (s *Storage) setBoltDB(key string, count int64) {
err := s.db.Set(s.config.Stat.BoltDB.Bucket, key, count)
if err != nil {
log.Println("BoltDB set error:", err.Error())
}
}
func (s *Storage) getBoltDB(key string) int64 {
var count int64
err := s.db.Get(s.config.Stat.BoltDB.Bucket, key, &count)
if err != nil {
log.Println("BoltDB get error:", err.Error())
}
return count
}