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

相关推荐
无关868824 分钟前
Redis Bitmaps 用户签到系统设计方案
数据库·redis·缓存
zzz_23685 小时前
【Java基础】链表的七十二变——从LRU缓存到手写浏览器前进后退
java·链表·缓存
IT策士8 小时前
Redis 从入门到精通:缓存经典难题 —— 穿透、击穿、雪崩
数据库·redis·缓存
IT策士8 小时前
Redis 从入门到精通:内存管理与淘汰策略
数据库·redis·缓存
AOwhisky1 天前
Redis 学习笔记(第四期):高可用与集群(哨兵 + Cluster + 容器化)
linux·运维·数据库·redis·笔记·学习·缓存
MXsoft6181 天前
**断网续传与本地缓存:弱网环境下的监控数据保障方案**
运维·缓存·自动化
xingyuzhisuan1 天前
缓存命中率提升方案:从 30% 优化至 82% 全流程优化记录
java·开发语言·缓存·ai
Konwledging1 天前
Cache Incoherent(缓存不一致)
缓存
慕木沐1 天前
【Spring AI + Google ADK 】流式输出时 outputKey 状态缓存失败的问题
人工智能·spring·缓存
swordbob1 天前
缓存延迟双删的两种策略
java·缓存