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

相关推荐
Familyism16 小时前
Redis
数据库·redis·缓存
Golinie1 天前
【Go | 从0实现简单分布式缓存】-1:LRU缓存淘汰策略与单机并发缓存
分布式·缓存·golang
清风微凉 aaa1 天前
Redis-03高级篇中-多级缓存:
数据库·redis·缓存
一个假的前端男1 天前
node 使用 Redis 缓存
数据库·redis·缓存
羊村懒哥1 天前
高性能内存对象缓存Memcached详细实验操作
数据库·缓存·memcached
左灯右行的爱情1 天前
Redis-缓存过期和内存淘汰
前端·redis·缓存
羊村懒哥1 天前
网络缓存加速技术解析:从诞生到演进
缓存
祈澈菇凉1 天前
如何清理cache-loader生成的缓存目录?
缓存
嘵奇1 天前
MyBatis框架七:缓存
缓存·mybatis
明达技术1 天前
网关断网缓存:让网络连接更可靠
缓存