用map+lock实现redis缓存

用map+lock实现redis缓存,第1张

用map+lock实现redis缓存 map + lock 实现 Redis缓存
·高并发的瓶颈就是数据库· 写这些只为笔记,不想被动收录

项目生产中 Redis 是最常用的,主要用与存放客户经常会访问的一些数据到内存里,从而减轻数据库的压力。根据需要获取你的系统不需要redis来增大开销,使用map+locak实现redis的主要功能是最好的选择.

//cache.go

var Cache *CacheMap

//初始化
func CacheInit() {
	if Cache == nil {
		Cache = NewCacheMap()
	}
}

//存放
func CachePut(key string, obj interface{}) {
	if obj == nil {
		return
	}
	CacheInit()
	Cache.Set(key, obj)
}

//按键获取
func CacheGet(key string) interface{} {
	CacheInit()
	return Cache.Get(key)
}

//按键获取 string
func CacheGetString(key string) string {
	CacheInit()

	v := Cache.Get(key)
	if v == nil {
		return ""
	}

	return v.(string)
}

//按键获取对象
func CacheGetObjt(key string) interface{} {
	CacheInit()
	return Cache.Get(key)
}

//清空
func CacheClear() {
	CacheInit()
	Cache.Clear()
}

//按键删除
func CacheClearKey(key string) {
	CacheInit()

	for k := range Cache.GetAllData() {
		if strings.HasPrefix(k.(string), key) {
			Cache.Delete(k.(string))
		}
	}
}


type CacheMap struct {
	lock *sync.RWMutex
	m    map[interface{}]interface{}
}

//新建缓存
func NewCacheMap() *CacheMap {
	
	return &CacheMap{
		lock: new(sync.RWMutex),
		m:    make(map[interface{}]interface{}),
	}
}

//获取缓存
func (cache *CacheMap) Get(k interface{}) interface{} {

	cache.lock.RLock()
	defer cache.lock.RUnlock()

	if val, ok := cache.m[k]; ok {
		return val
	}

	return nil
}

//开始缓存
func (cache *CacheMap) Set(k interface{}, v interface{}) bool {

	cache.lock.Lock()
	defer cache.lock.Unlock()

	if val, ok := cache.m[k]; !ok {
		cache.m[k] = v
	} else if val != v {
		cache.m[k] = v
	} else {
		return false
	}

	return true
}

// 如果缓存已经存在就返回true
func (cache *CacheMap) Check(k interface{}) bool {

	cache.lock.RLock()
	defer cache.lock.RUnlock()

	if _, ok := cache.m[k]; !ok {
		return false
	}
	return true

}

//删除一条数据
func (cache *CacheMap) Delete(k interface{}) {
	cache.lock.Lock()
	defer cache.lock.Unlock()

	delete(cache.m, k)
}

//获取所有缓存数据
func (cache *CacheMap) GetAllData() map[interface{}]interface{} {

	cache.lock.Lock()
	defer cache.lock.Unlock()

	result := make(map[interface{}]interface{})
	for k, v := range cache.m {
		result[k] = v
	}

	return result
}

//清空缓存
func (cache *CacheMap) Clear() {

	cache.lock.Lock()
	defer cache.lock.Unlock()

	cache.m = make(map[interface{}]interface{})

}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5681625.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存