1
0
mirror of https://github.com/astaxie/beego.git synced 2025-06-14 11:30:39 +00:00
cache add function
// IncrBy increase counter by num.
IncrBy(key string, num int)
// DecrBy decrease counter by num.
DecrBy(key string, num int)
This commit is contained in:
hible
2018-07-31 17:19:09 +08:00
parent a09bafbf2a
commit c7c0b01ec5
10 changed files with 284 additions and 1 deletions

29
cache/ssdb/ssdb.go vendored
View File

@ -124,6 +124,20 @@ func (rc *Cache) Incr(key string) error {
return err
}
// IncrBy increase counter by num.
func (rc *Cache) IncrBy(key string, num int) error {
if num < 1 {
return errors.New("increase num should be a positive number")
}
if rc.conn == nil {
if err := rc.connectInit(); err != nil {
return err
}
}
_, err := rc.conn.Do("incr", key, num)
return err
}
// Decr decrease counter.
func (rc *Cache) Decr(key string) error {
if rc.conn == nil {
@ -135,6 +149,21 @@ func (rc *Cache) Decr(key string) error {
return err
}
// DecrBy decrease counter by num.
func (rc *Cache) DecrBy(key string, num int) error {
if num < 1 {
return errors.New("decrease num should be a positive number")
}
if rc.conn == nil {
if err := rc.connectInit(); err != nil {
return err
}
}
_, err := rc.conn.Do("incr", key, -num)
return err
}
// IsExist check value exists in memcache.
func (rc *Cache) IsExist(key string) bool {
if rc.conn == nil {

View File

@ -40,6 +40,7 @@ func TestSsdbcacheCache(t *testing.T) {
if err = ssdb.Put("ssdb", "2", timeoutDuration); err != nil {
t.Error("set Error", err)
}
if err = ssdb.Incr("ssdb"); err != nil {
t.Error("incr Error", err)
}
@ -48,10 +49,30 @@ func TestSsdbcacheCache(t *testing.T) {
t.Error("get err")
}
if err = ssdb.IncrBy("ssdb", 2); err != nil {
t.Error("incr Error", err)
}
if v, err := strconv.Atoi(ssdb.Get("ssdb").(string)); err != nil || v != 5 {
t.Error("get err")
}
if err = ssdb.DecrBy("ssdb", 2); err != nil {
t.Error("decr error")
}
if v, err := strconv.Atoi(ssdb.Get("ssdb").(string)); err != nil || v != 3 {
t.Error("get err")
}
if err = ssdb.Decr("ssdb"); err != nil {
t.Error("decr error")
}
if v, err := strconv.Atoi(ssdb.Get("ssdb").(string)); err != nil || v != 2 {
t.Error("get err")
}
// test del
if err = ssdb.Put("ssdb", "3", timeoutDuration); err != nil {
t.Error("set Error", err)