]> 127.0.0.1 Git - part/.git/commitdiff
109 v0.5.0
authorqydysky <qydysky@foxmail.com>
Thu, 1 Apr 2021 10:02:59 +0000 (18:02 +0800)
committerqydysky <qydysky@foxmail.com>
Thu, 1 Apr 2021 10:02:59 +0000 (18:02 +0800)
tmplKV/tmplKV.go [new file with mode: 0644]
tmplKV/tmplKV_test.go [new file with mode: 0644]

diff --git a/tmplKV/tmplKV.go b/tmplKV/tmplKV.go
new file mode 100644 (file)
index 0000000..8e130d3
--- /dev/null
@@ -0,0 +1,64 @@
+package part
+
+import (
+       "time"
+       syncmap "github.com/qydysky/part/map"
+)
+
+type tmplKV struct {
+       now int64
+       kvt_map syncmap.Map
+}
+
+type tmplKV_item struct {
+       kv interface{}
+       kt int64
+}
+
+// 初始化一个带超时机制的Key-Value储存器
+func New_tmplKV() (*tmplKV) {
+
+       s := &tmplKV{}
+
+       go func(){
+               ticker := time.NewTicker(time.Second)
+               for{
+                       s.now = (<- ticker.C).Unix()
+               }
+       }()
+
+       return s
+}
+
+// 设置Key Value Exp(有效秒数)
+func (s *tmplKV) Set(key,value interface{},exp int64) {
+       s.kvt_map.Store(key, tmplKV_item{
+               kv: value,
+               kt: s.now+exp,
+       })
+}
+
+//获取Value 及是否有效
+func (s *tmplKV) Get(key interface{}) (isLive bool,value interface{}){
+       tmp, ok := s.kvt_map.Load(key)
+
+       item,_ := tmp.(tmplKV_item)
+       value = item.kv
+
+       isLive = ok && s.now <= item.kt
+       if !isLive && ok {
+               s.kvt_map.Delete(key)
+       }
+       return
+}
+
+//检查Key Value是否对应及有效
+func (s *tmplKV) Check(key,value interface{}) bool {
+       ok,v := s.Get(key)
+       return ok && v == value
+}
+
+//当前储存器键值数量
+func (s *tmplKV) Len() (int64,int) {
+       return s.now,s.kvt_map.Len()
+}
diff --git a/tmplKV/tmplKV_test.go b/tmplKV/tmplKV_test.go
new file mode 100644 (file)
index 0000000..aa7b244
--- /dev/null
@@ -0,0 +1,16 @@
+package part
+
+import (
+       "time"
+       "testing"
+)
+
+func Test_tmplKV(t *testing.T) {
+       s := New_tmplKV()
+       s.Set("a",`a`,1)
+       if !s.Check("a",`a`) {t.Error(`no match1`)}
+       s.Set("a",`b`,1)
+       if !s.Check("a",`b`) {t.Error(`no match2`)}
+       time.Sleep(time.Second*time.Duration(1))
+       if s.Check("a",`b`) {t.Error(`no TO1`)}
+}