2016-09-19 08:19:20 +00:00
|
|
|
package leveldb
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2017-01-19 09:08:12 +00:00
|
|
|
"strconv"
|
2022-02-03 09:03:37 +00:00
|
|
|
"sync"
|
2017-01-19 09:08:12 +00:00
|
|
|
|
2016-09-19 08:19:20 +00:00
|
|
|
"github.com/appleboy/gorush/config"
|
2017-06-24 16:48:48 +00:00
|
|
|
"github.com/syndtr/goleveldb/leveldb"
|
2016-09-19 08:19:20 +00:00
|
|
|
)
|
|
|
|
|
2020-04-23 07:39:24 +00:00
|
|
|
func (s *Storage) setLevelDB(key string, count int64) {
|
2016-09-19 08:19:20 +00:00
|
|
|
value := fmt.Sprintf("%d", count)
|
2020-04-23 07:39:24 +00:00
|
|
|
_ = s.db.Put([]byte(key), []byte(value), nil)
|
2016-09-19 08:19:20 +00:00
|
|
|
}
|
|
|
|
|
2022-02-03 09:03:37 +00:00
|
|
|
func (s *Storage) getLevelDB(key string) int64 {
|
2020-04-23 07:39:24 +00:00
|
|
|
data, _ := s.db.Get([]byte(key), nil)
|
2022-02-03 09:03:37 +00:00
|
|
|
count, _ := strconv.ParseInt(string(data), 10, 64)
|
|
|
|
return count
|
2016-09-19 08:19:20 +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-09-19 08:19:20 +00:00
|
|
|
return &Storage{
|
|
|
|
config: config,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Storage is interface structure
|
|
|
|
type Storage struct {
|
2021-08-02 06:07:30 +00:00
|
|
|
config *config.ConfYaml
|
2020-04-23 07:39:24 +00:00
|
|
|
db *leveldb.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.setLevelDB(key, s.getLevelDB(key)+count)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Storage) Set(key string, count int64) {
|
|
|
|
s.lock.Lock()
|
|
|
|
defer s.lock.Unlock()
|
|
|
|
s.setLevelDB(key, count)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Storage) Get(key string) int64 {
|
|
|
|
s.lock.RLock()
|
|
|
|
defer s.lock.RUnlock()
|
|
|
|
return s.getLevelDB(key)
|
2016-09-19 08:19:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Init client storage.
|
|
|
|
func (s *Storage) Init() error {
|
2020-04-23 07:39:24 +00:00
|
|
|
var err error
|
|
|
|
s.db, err = leveldb.OpenFile(s.config.Stat.LevelDB.Path, nil)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Close the storage connection
|
|
|
|
func (s *Storage) Close() error {
|
|
|
|
if s.db == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return s.db.Close()
|
2016-09-19 08:19:20 +00:00
|
|
|
}
|