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

相关推荐
nvd115 分钟前
ArgoCD 双层轮询深入拆解:从 redis-app.yaml 注册到缓存重建的完整链路
redis·缓存·argocd
xiaoxiangsiyan23 分钟前
LNMP + Redis Sentinel 高可用架构部署手册(续)
运维·网络·数据库·redis·缓存·架构·sentinel
難釋懷4 小时前
Nginx外置缓存-redis2-nginx-module
nginx·缓存·junit
LearnYard5 小时前
Android存储空间清理策略对比:缓存识别与多种清理方案的技术分析
缓存·智能手机
时空自由民.6 小时前
STM32的缓存Cache
stm32·嵌入式硬件·缓存
ai_coder_ai20 小时前
分布式缓存架构设计与实践
分布式·缓存
Wang's Blog1 天前
AI Agent白手起家23: 大模型速率限制应对与缓存机制实践
人工智能·缓存
网教盟人才服务平台1 天前
Redis Key集中过期引发的流量雪崩实战解析
数据库·redis·缓存
Ivan CloudBay1 天前
网站为什么会使用缓存?
服务器·网络·缓存·云服务器
_oP_i1 天前
Another Redis Desktop Manager更新
数据库·redis·缓存