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

相关推荐
UQI-LIUWJ39 分钟前
计算机组成笔记:缓存替换算法
笔记·缓存
harmful_sheep2 小时前
Spring 为何需要三级缓存解决循环依赖,而不是二级缓存
java·spring·缓存
软件2053 小时前
【redis使用场景——缓存——数据淘汰策略】
数据库·redis·缓存
加勒比海涛4 小时前
Spring Cloud Gateway 实战:从网关搭建到过滤器与跨域解决方案
数据库·redis·缓存
香饽饽~、5 小时前
【第十一篇】SpringBoot缓存技术
java·开发语言·spring boot·后端·缓存·intellij-idea
MonkeyKing_sunyuhua10 小时前
Guava Cache 本地项目缓存
缓存·guava
笨手笨脚の10 天前
Redis 源码分析-Redis 中的事件驱动
数据库·redis·缓存·select·nio·epoll·io模型
(:满天星:)10 天前
Redis哨兵模式深度解析与实战部署
linux·服务器·网络·数据库·redis·缓存·centos
哆啦A梦的口袋呀10 天前
《HTTP权威指南》 第7章 缓存
网络协议·http·缓存
大模型最新论文速读10 天前
Agent成本降低46%:缓存规划器的思路模板
人工智能·深度学习·机器学习·缓存·语言模型·自然语言处理