使用go_concurrent_map 管理 并发更新缓存

在后台服务中,为了提速,我在内存还做了一个告诉缓存来管理用户信息,根据更新通知,或者定时去redis中同步信息,那么在加载或者更新某个用户元素时,要防止并发,

当:

1)如果内存缓存没有;

2)去数据库或者redis加载;

3)添加到内存缓存;

这里就有个并发重复的可能性;

所以,这里要做一个加锁的插入或者更新,使用go_concurrent_map就十分方便:

Go 复制代码
// https://github.com/robinfoxnan/go_concurrent_map
// 这里使用一个支持高并发的map来管理会话
type UserCache struct {
	//lock sync.Mutex

	userMap utils.ConcurrentMap[int64, *User]
}

// 如果没有,则从redis中查找,如果redis中没有,则从数据库中查找
func (uc *UserCache) GetUser(uid int64) (*User, bool) {

	user, err := uc.userMap.Get(uid)
	return user, err
}

// 更新时候的回调函数,如果未设置,则
func updateInsertUser(exist bool, oldUser *User, newUser *User) *User {
	if exist == false {
		return newUser
	} else {
		oldUser.MergeUser(newUser)
		return oldUser
	}
}

// 这里可能会有并发冲突,需要解决的就是session列表需要合并
func (uc *UserCache) SetOrUpdateUser(uid int64, user *User) {
	uc.userMap.Upsert(uid, user, updateInsertUser)
}

这个类在插入时候,可以检测是否存在,并通过回调函数来决定是插入还是更新;这个加锁已经放在插入函数中完成了;

详细代码请查看:GitHub - robinfoxnan/BirdTalkServer: An open source IM system

相关推荐
程序员黎剑10 小时前
Redis缓存击穿:热点Key过期打崩数据库的3种解决方案
数据库·redis·缓存
xixiaoyunya10 小时前
Redis 缓存一致性方案深度对比:从理论到工程落地
redis·spring·缓存
Zenova EdgeOS12 小时前
工业边缘双写一致性:从缓存到多 DB 的工程实战
数据库·缓存·边缘计算·工业边缘
职场的momo13 小时前
16384个槽怎么搬?解析Redis集群迁移与脑裂防御
数据库·redis·缓存
cfm_291413 小时前
Redis大Key与热Key分析
redis·缓存
TheBestRucy13 小时前
Python九阳神功之陆:数据库持久化与缓存·乾坤大挪移
数据库·python·缓存
TDengine (老段)14 小时前
TDengine 内存管理 — 池化、缓存、回收
大数据·数据库·物联网·缓存·时序数据库·tdengine·涛思数据
空堂与归14 小时前
南大 AI 课 Token 自费:用缓存命中率算一学期账单
人工智能·缓存·ai·deepseek
吴声子夜歌15 小时前
Guava——缓存
缓存·guava