From 545fc68481c6b72859408cd42aadc25c6b16984b Mon Sep 17 00:00:00 2001 From: John Date: Thu, 29 Mar 2018 14:31:45 +0800 Subject: [PATCH] =?UTF-8?q?gcache=E5=A2=9E=E5=8A=A0=E5=86=85=E5=AD=98?= =?UTF-8?q?=E9=94=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- g/os/gcache/gcache.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/g/os/gcache/gcache.go b/g/os/gcache/gcache.go index 38eddad6b..ad0ae5a40 100644 --- a/g/os/gcache/gcache.go +++ b/g/os/gcache/gcache.go @@ -96,6 +96,20 @@ func BatchRemove(keys []string) { cache.BatchRemove(keys) } +// 基于内存缓存的锁,锁成功返回true,失败返回false,当失败时表示有其他的锁存在 +func Lock(key string, expire int64) bool { + if v := cache.Get(key); v != nil { + return false + } + cache.Set(key, struct {}{}, expire) + return true +} + +// 解除基于内存缓存的锁 +func Unlock(key string) { + cache.Remove(key) +} + // 获得所有的键名,组成字符串数组返回 func Keys() []string { return cache.Keys() @@ -175,6 +189,20 @@ func (c *Cache) BatchSet(data map[string]interface{}, expire int64) { } } +// 基于内存缓存的锁,锁成功返回true,失败返回false,当失败时表示有其他的锁存在 +func (c *Cache) Lock(key string, expire int64) bool { + if v := c.Get(key); v != nil { + return false + } + c.Set(key, struct {}{}, expire) + return true +} + +// 解除基于内存缓存的锁 +func (c *Cache) Unlock(key string) { + c.Remove(key) +} + // 获取指定键名的值 func (c *Cache) Get(key string) interface{} { c.dmu.RLock()