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

相关推荐
程序员夏洛7 小时前
Redis 数据过期后的删除策略是什么?
数据库·redis·缓存
鱼鳞_7 小时前
热门八股-Redis
数据库·redis·缓存
hweiyu009 小时前
Redis命令:MIGRATE
redis·缓存
A.说学逗唱的Coke10 小时前
【人工智能专题】Redis 杀进 AI 数据层:向量搜索、语义缓存与 Agent 记忆工程从入门到踩坑
人工智能·redis·缓存
XiYang-DING11 小时前
地图城市缓存优化:ApplicationReadyEvent + Caffeine + Redis + Redisson 分布式锁
redis·分布式·缓存
智购科技无人售货机厂家1 天前
2026自动售货机制冷系统维护指南:从散热器清洁到压缩机换油的工程实践~YH
运维·redis·物联网·缓存·架构
2601_962128411 天前
SpringBoot篇(缓存层)
java·spring boot·缓存
mmsy10241 天前
缓存知识点总结
java·spring·缓存
garmin Chen1 天前
redis面试题
java·数据库·redis·缓存
程序员夏洛2 天前
Redis 的 Red Lock 是什么?你了解吗?
数据库·redis·缓存