优化你的应用结构和实现Redis缓存

项目地址:https://github.com/EDDYCJY/go-gin-example

如果对你有所帮助,欢迎点个 Star ?

前言

之前就在想,不少教程或示例的代码设计都是一步到位的(也没问题)

但实际操作的读者真的能够理解透彻为什么吗?左思右想,有了今天这一章的内容,我认为实际经历过一遍印象会更加深刻

规划

在本章节,将介绍以下功能的整理:

  • 抽离、分层业务逻辑:减轻 routers/*.go 内的 api方法的逻辑(但本文暂不分层 repository,这块逻辑还不重)
  • 增加容错性:对 gorm 的错误进行判断
  • Redis缓存:对获取数据类的接口增加缓存设置
  • 减少重复冗余代码

问题在哪?

在规划阶段我们发现了一个问题,这是目前的伪代码:

  1. if ! HasErrors() {
  2. if ExistArticleByID(id) {
  3. DeleteArticle(id)
  4. code = e.SUCCESS
  5. } else {
  6. code = e.ERROR_NOT_EXIST_ARTICLE
  7. }
  8. } else {
  9. for _, err := range valid.Errors {
  10. logging.Info(err.Key, err.Message)
  11. }
  12. }
  13. c.JSON(http.StatusOK, gin.H{
  14. "code": code,
  15. "msg": e.GetMsg(code),
  16. "data": make(map[string]string),
  17. })

如果加上规划内的功能逻辑呢,伪代码会变成:

  1. if ! HasErrors() {
  2. exists, err := ExistArticleByID(id)
  3. if err == nil {
  4. if exists {
  5. err = DeleteArticle(id)
  6. if err == nil {
  7. code = e.SUCCESS
  8. } else {
  9. code = e.ERROR_XXX
  10. }
  11. } else {
  12. code = e.ERROR_NOT_EXIST_ARTICLE
  13. }
  14. } else {
  15. code = e.ERROR_XXX
  16. }
  17. } else {
  18. for _, err := range valid.Errors {
  19. logging.Info(err.Key, err.Message)
  20. }
  21. }
  22. c.JSON(http.StatusOK, gin.H{
  23. "code": code,
  24. "msg": e.GetMsg(code),
  25. "data": make(map[string]string),
  26. })

如果缓存的逻辑也加进来,后面慢慢不断的迭代,岂不是会变成如下图一样?

image

现在我们发现了问题,应及时解决这个代码结构问题,同时把代码写的清晰、漂亮、易读易改也是一个重要指标

如何改?

在左耳朵耗子的文章中,这类代码被称为 “箭头型” 代码,有如下几个问题:

1、我的显示器不够宽,箭头型代码缩进太狠了,需要我来回拉水平滚动条,这让我在读代码的时候,相当的不舒服

2、除了宽度外还有长度,有的代码的 if-else 里的 if-else 里的 if-else 的代码太多,读到中间你都不知道中间的代码是经过了什么样的层层检查才来到这里的

总而言之,“箭头型代码”如果嵌套太多,代码太长的话,会相当容易让维护代码的人(包括自己)迷失在代码中,因为看到最内层的代码时,你已经不知道前面的那一层一层的条件判断是什么样的,代码是怎么运行到这里的,所以,箭头型代码是非常难以维护和Debug的。

简单的来说,就是让出错的代码先返回,前面把所有的错误判断全判断掉,然后就剩下的就是正常的代码了

(注意:本段引用自耗子哥的 如何重构“箭头型”代码,建议细细品尝)

落实

本项目将对既有代码进行优化和实现缓存,希望你习得方法并对其他地方也进行优化

第一步:完成 Redis 的基础设施建设(需要你先装好 Redis)

第二步:对现有代码进行拆解、分层(不会贴上具体步骤的代码,希望你能够实操一波,加深理解?)

Redis

一、配置

打开 conf/app.ini 文件,新增配置:

  1. ...
  2. [redis]
  3. Host = 127.0.0.1:6379
  4. Password =
  5. MaxIdle = 30
  6. MaxActive = 30
  7. IdleTimeout = 200

二、缓存 Prefix

打开 pkg/e 目录,新建 cache.go,写入内容:

  1. package e
  2. const (
  3. CACHE_ARTICLE = "ARTICLE"
  4. CACHE_TAG = "TAG"
  5. )

三、缓存 Key

(1)、打开 service 目录,新建 cache_service/article.go

写入内容:传送门

(2)、打开 service 目录,新建 cache_service/tag.go

写入内容:传送门

这一部分主要是编写获取缓存 KEY 的方法,直接参考传送门即可

四、Redis 工具包

打开 pkg 目录,新建 gredis/redis.go,写入内容:

  1. package gredis
  2. import (
  3. "encoding/json"
  4. "time"
  5. "github.com/gomodule/redigo/redis"
  6. "github.com/EDDYCJY/go-gin-example/pkg/setting"
  7. )
  8. var RedisConn *redis.Pool
  9. func Setup() error {
  10. RedisConn = &redis.Pool{
  11. MaxIdle: setting.RedisSetting.MaxIdle,
  12. MaxActive: setting.RedisSetting.MaxActive,
  13. IdleTimeout: setting.RedisSetting.IdleTimeout,
  14. Dial: func() (redis.Conn, error) {
  15. c, err := redis.Dial("tcp", setting.RedisSetting.Host)
  16. if err != nil {
  17. return nil, err
  18. }
  19. if setting.RedisSetting.Password != "" {
  20. if _, err := c.Do("AUTH", setting.RedisSetting.Password); err != nil {
  21. c.Close()
  22. return nil, err
  23. }
  24. }
  25. return c, err
  26. },
  27. TestOnBorrow: func(c redis.Conn, t time.Time) error {
  28. _, err := c.Do("PING")
  29. return err
  30. },
  31. }
  32. return nil
  33. }
  34. func Set(key string, data interface{}, time int) error {
  35. conn := RedisConn.Get()
  36. defer conn.Close()
  37. value, err := json.Marshal(data)
  38. if err != nil {
  39. return err
  40. }
  41. _, err = conn.Do("SET", key, value)
  42. if err != nil {
  43. return err
  44. }
  45. _, err = conn.Do("EXPIRE", key, time)
  46. if err != nil {
  47. return err
  48. }
  49. return nil
  50. }
  51. func Exists(key string) bool {
  52. conn := RedisConn.Get()
  53. defer conn.Close()
  54. exists, err := redis.Bool(conn.Do("EXISTS", key))
  55. if err != nil {
  56. return false
  57. }
  58. return exists
  59. }
  60. func Get(key string) ([]byte, error) {
  61. conn := RedisConn.Get()
  62. defer conn.Close()
  63. reply, err := redis.Bytes(conn.Do("GET", key))
  64. if err != nil {
  65. return nil, err
  66. }
  67. return reply, nil
  68. }
  69. func Delete(key string) (bool, error) {
  70. conn := RedisConn.Get()
  71. defer conn.Close()
  72. return redis.Bool(conn.Do("DEL", key))
  73. }
  74. func LikeDeletes(key string) error {
  75. conn := RedisConn.Get()
  76. defer conn.Close()
  77. keys, err := redis.Strings(conn.Do("KEYS", "*"+key+"*"))
  78. if err != nil {
  79. return err
  80. }
  81. for _, key := range keys {
  82. _, err = Delete(key)
  83. if err != nil {
  84. return err
  85. }
  86. }
  87. return nil
  88. }

在这里我们做了一些基础功能封装

1、设置 RedisConn 为 redis.Pool(连接池)并配置了它的一些参数:

  • Dial:提供创建和配置应用程序连接的一个函数

  • TestOnBorrow:可选的应用程序检查健康功能

  • MaxIdle:最大空闲连接数

  • MaxActive:在给定时间内,允许分配的最大连接数(当为零时,没有限制)

  • IdleTimeout:在给定时间内将会保持空闲状态,若到达时间限制则关闭连接(当为零时,没有限制)

2、封装基础方法

文件内包含 Set、Exists、Get、Delete、LikeDeletes 用于支撑目前的业务逻辑,而在里面涉及到了如方法:

(1)RedisConn.Get():在连接池中获取一个活跃连接

(2)conn.Do(commandName string, args ...interface{}):向 Redis 服务器发送命令并返回收到的答复

(3)redis.Bool(reply interface{}, err error):将命令返回转为布尔值

(4)redis.Bytes(reply interface{}, err error):将命令返回转为 Bytes

(5)redis.Strings(reply interface{}, err error):将命令返回转为 []string

redigo 中包含大量类似的方法,万变不离其宗,建议熟悉其使用规则和 Redis命令 即可

到这里为止,Redis 就可以愉快的调用啦。另外受篇幅限制,这块的深入讲解会另外开设!

拆解、分层

在先前规划中,引出几个方法去优化我们的应用结构

  • 错误提前返回
  • 统一返回方法
  • 抽离 Service,减轻 routers/api 的逻辑,进行分层
  • 增加 gorm 错误判断,让错误提示更明确(增加内部错误码)

编写返回方法

要让错误提前返回,c.JSON 的侵入是不可避免的,但是可以让其更具可变性,指不定哪天就变 XML 了呢?

1、打开 pkg 目录,新建 app/request.go,写入文件内容:

  1. package app
  2. import (
  3. "github.com/astaxie/beego/validation"
  4. "github.com/EDDYCJY/go-gin-example/pkg/logging"
  5. )
  6. func MarkErrors(errors []*validation.Error) {
  7. for _, err := range errors {
  8. logging.Info(err.Key, err.Message)
  9. }
  10. return
  11. }

2、打开 pkg 目录,新建 app/response.go,写入文件内容:

  1. package app
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "github.com/EDDYCJY/go-gin-example/pkg/e"
  5. )
  6. type Gin struct {
  7. C *gin.Context
  8. }
  9. func (g *Gin) Response(httpCode, errCode int, data interface{}) {
  10. g.C.JSON(httpCode, gin.H{
  11. "code": httpCode,
  12. "msg": e.GetMsg(errCode),
  13. "data": data,
  14. })
  15. return
  16. }

这样子以后如果要变动,直接改动 app 包内的方法即可

修改既有逻辑

打开 routers/api/v1/article.go,查看修改 GetArticle 方法后的代码为:

  1. func GetArticle(c *gin.Context) {
  2. appG := app.Gin{c}
  3. id := com.StrTo(c.Param("id")).MustInt()
  4. valid := validation.Validation{}
  5. valid.Min(id, 1, "id").Message("ID必须大于0")
  6. if valid.HasErrors() {
  7. app.MarkErrors(valid.Errors)
  8. appG.Response(http.StatusOK, e.INVALID_PARAMS, nil)
  9. return
  10. }
  11. articleService := article_service.Article{ID: id}
  12. exists, err := articleService.ExistByID()
  13. if err != nil {
  14. appG.Response(http.StatusOK, e.ERROR_CHECK_EXIST_ARTICLE_FAIL, nil)
  15. return
  16. }
  17. if !exists {
  18. appG.Response(http.StatusOK, e.ERROR_NOT_EXIST_ARTICLE, nil)
  19. return
  20. }
  21. article, err := articleService.Get()
  22. if err != nil {
  23. appG.Response(http.StatusOK, e.ERROR_GET_ARTICLE_FAIL, nil)
  24. return
  25. }
  26. appG.Response(http.StatusOK, e.SUCCESS, article)
  27. }

这里有几个值得变动点,主要是在内部增加了错误返回,如果存在错误则直接返回。另外进行了分层,业务逻辑内聚到了 service 层中去,而 routers/api(controller)显著减轻,代码会更加的直观

例如 service/article_service 下的 articleService.Get() 方法:

  1. func (a *Article) Get() (*models.Article, error) {
  2. var cacheArticle *models.Article
  3. cache := cache_service.Article{ID: a.ID}
  4. key := cache.GetArticleKey()
  5. if gredis.Exists(key) {
  6. data, err := gredis.Get(key)
  7. if err != nil {
  8. logging.Info(err)
  9. } else {
  10. json.Unmarshal(data, &cacheArticle)
  11. return cacheArticle, nil
  12. }
  13. }
  14. article, err := models.GetArticle(a.ID)
  15. if err != nil {
  16. return nil, err
  17. }
  18. gredis.Set(key, article, 3600)
  19. return article, nil
  20. }

而对于 gorm 的 错误返回设置,只需要修改 models/article.go 如下:

  1. func GetArticle(id int) (*Article, error) {
  2. var article Article
  3. err := db.Where("id = ? AND deleted_on = ? ", id, 0).First(&article).Related(&article.Tag).Error
  4. if err != nil && err != gorm.ErrRecordNotFound {
  5. return nil, err
  6. }
  7. return &article, nil
  8. }

习惯性增加 .Error,把控绝大部分的错误。另外需要注意一点,在 gorm 中,查找不到记录也算一种 “错误” 哦

最后

显然,本章节并不是你跟着我敲系列。我给你的课题是 “实现 Redis 缓存并优化既有的业务逻辑代码”

让其能够不断地适应业务的发展,让代码更清晰易读,且呈层级和结构性

如果有疑惑,可以到 go-gin-example 看看我是怎么写的,你是怎么写的,又分别有什么优势、劣势,取长补短一波?

参考

本系列示例代码

推荐阅读