业务小模块日记【1】

1.3k 词

业务逻辑-cdn持久化存储缓存以及更新cdn缓存

这里以通过微信登录时缓存微信头像图片为例

cdn缓存是什么:

cdn是网络上提供缓存服务的节点,用于减轻访问压力,并降低对第三方的依赖

比如用户在通过微信登录的时候会提供自己头像的url, 当我们不使用cdn缓存的时候,由于微信头像的url是不稳定的,当你的微信头像更换之后,原来的url会失效,最终导致网页根据该url解析的头像图片失效

而如果采用cdn缓存,会将当前url的图片缓存到cdn节点,之后网页头像图片的获取就从cdn来,哪怕原头像图片对应的微信url失效,网页头像依旧正常

接下来是更新cdn缓存和网页头像的一套业务逻辑模块,头像url分为以下三种:

  • userInfo.AvatarUrl为新头像:当前这次登录时获取到最新的微信头像
  • user.Avatar为网页头像:网页显示的头像
  • user.PermanentAvatar为获取cdn缓存的url
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
···
······
//在覆盖之前捕获之前存储的旧头像
oldAvatarUrl := getUserProperty(user, wechat_avater_url)
setUserProperty(user, wechat_avater_url, userInfo.AvatarUrl)
//对网页头像操作:如果网页头像为空/默认/旧,则设置网页头像为新头像
if user.Avatar == "" || user.Avatar == organization.DefaultAvatar || user.Avatar == oldAvatarUrl {
user.Avatar = userInfo.AvatarUrl
}
//对cdn缓存头像图片操作:如果缓存不存在/旧头像与新头像不一样,则更新cdn缓存头像
if oldAvatarUrl != userInfo.AvatarUrl || user.PermanentAvatar == "" {
//上传新头像到cdn缓存并返回新cdn缓存的url
permanentAvatarUrl := getPermanentAvatarUrl(user.Owner, user.Name, userInfo.AvatarUrl, true)
if err != nil {
log.Printf("Failed to upload OAuth avatar for user %s: %v", user.Name, err)
} else if permanentAvatarUrl != "" {
user.PermanentAvatar = permanentAvatarUrl
if user.Avatar == userInfo.AvatarUrl {
//将网页头像从新头像url(第三方不稳定url)改为获取cdn缓存的稳定url
user.Avatar = permanentAvatarUrl
}
}
}
······
···
留言