2016-05-02 06:52:38 +00:00
|
|
|
package boltdb
|
|
|
|
|
|
|
|
import (
|
2017-08-24 03:25:05 +00:00
|
|
|
"log"
|
2022-02-03 09:03:37 +00:00
|
|
|
"sync"
|
2017-08-24 03:25:05 +00:00
|
|
|
|
2016-05-03 01:56:59 +00:00
|
|
|
"github.com/appleboy/gorush/config"
|
2020-04-23 07:58:03 +00:00
|
|
|
"github.com/asdine/storm/v3"
|
2016-05-02 12:22:37 +00:00
|
|
|
)
|
|
|
|
|
2016-07-31 13:10:59 +00:00
|
|
|
// New func implements the storage interface for gorush (https://github.com/appleboy/gorush)
|
2021-08-02 06:07:30 +00:00
|
|
|
func New(config *config.ConfYaml) *Storage {
|
2016-05-02 06:52:38 +00:00
|
|
|
return &Storage{
|
|
|
|
config: config,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-08-01 02:57:00 +00:00
|
|
|
// Storage is interface structure
|
2016-05-02 06:52:38 +00:00
|
|
|
type Storage struct {
|
2021-08-02 06:07:30 +00:00
|
|
|
config *config.ConfYaml
|
2020-04-23 07:39:24 +00:00
|
|
|
db *storm.DB
|
2022-02-03 09:03:37 +00:00
|
|
|
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)
|
2016-05-02 06:52:38 +00:00
|
|
|
}
|
|
|
|
|
2016-08-01 02:57:00 +00:00
|
|
|
// Init client storage.
|
2016-05-02 12:22:37 +00:00
|
|
|
func (s *Storage) Init() error {
|
2020-04-23 07:39:24 +00:00
|
|
|
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()
|
2016-05-02 06:52:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Storage) setBoltDB(key string, count int64) {
|
2020-04-23 07:39:24 +00:00
|
|
|
err := s.db.Set(s.config.Stat.BoltDB.Bucket, key, count)
|
2017-08-24 03:25:05 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Println("BoltDB set error:", err.Error())
|
|
|
|
}
|
2016-05-02 06:52:38 +00:00
|
|
|
}
|
|
|
|
|
2022-02-03 09:03:37 +00:00
|
|
|
func (s *Storage) getBoltDB(key string) int64 {
|
|
|
|
var count int64
|
|
|
|
err := s.db.Get(s.config.Stat.BoltDB.Bucket, key, &count)
|
2017-08-24 03:25:05 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Println("BoltDB get error:", err.Error())
|
|
|
|
}
|
2020-09-04 03:01:21 +00:00
|
|
|
return count
|
|
|
|
}
|