使用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

相关推荐
xto_coo10 分钟前
锡膏存储方法有哪些?
缓存
犹豫的大炮2 小时前
jQuery最核心的基础设施之一——数据缓存模块进化史
前端·缓存·jquery
宠友信息3 小时前
资源权限与钱包流水在即时通讯源码后端架构中的设计
java·spring boot·redis·websocket·缓存
rebibabo4 小时前
Java高并发底层原理(六)—— 多核 CPU 如何保持缓存一致
java·缓存·cas·缓存一致性·cache line·longadder·mesi协议
nVisual4 小时前
nVisual:AI驱动的智能排障,平均响应时间缩短40%
android·人工智能·缓存
阿拉斯攀登5 小时前
RAG 性能优化:缓存、批量与并发
人工智能·缓存·性能优化·embedding·agent·loop·rag
XLYcmy1 天前
核内调度问题的分层优化:缓存管理与性能均衡策略 模型评价 模型缺点与改进方向
缓存·ai·启发式算法·图神经网络·遗传算法·数模·模拟退火
随风一样自由1 天前
【前端+React+缓存竞态】导航切换缓存刷新机制
前端·react.js·缓存
桌面运维家2 天前
如何用半缓存云桌面将服务器硬盘容量扩展至本地终端?
运维·服务器·缓存
YOU OU2 天前
Redis初识
数据库·redis·缓存