dongpu4141 2018-01-11 00:53
浏览 310

Xorm Redis缓存似乎无法正常工作

I currently develop golang projects with xorm.

I want to use a cache to manage the result of sql queries called once. I expected that sql requests would be called once, and would not be called again, but they do get called again.

Also, Redis keys that get created do not appear in redis-cli(keys *).

Why are my sql queries getting called more than once?

package main

import (
    "github.com/go-xorm/xorm"
    _ "github.com/go-sql-driver/mysql"
    xrc "github.com/go-xorm/xorm-redis-cache"
)

type User struct {
    Id int
    Name string
}

func main() {
    engine, err := xorm.NewEngine("mysql", "root:@/xorm_test_db")
    if nil != err {
        log.Fatal(err)
    }
    engine.ShowSQL(true)

    cacher := xrc.NewRedisCacher("localhost:6379", "", xrc.DEFAULT_EXPIRATION, engine.Logger())
    engine.SetDefaultCacher(cacher)

    engine.Get(User{Id: 1})
    engine.Get(User{Id: 1})
}
  • 写回答

2条回答 默认 最新

  • doulu1544 2018-01-11 14:20
    关注

    Two things has to be addressed for the caching to work properly:

    1. Table must have a Primary Key for it to be cached. So Id can be made as Primary Key as follows:

      type User struct {
          Id   int `xorm:"pk"`
          Name string
      }
      
    2. The type User must be registered using Golang's encoding/gob package:

      gob.Register(new(User))
      

    Don't forget to drop the existing table and sync the new User structure.

    // Drop the existing table
    DROP TABLE user;
    
    // Sync the User struct to table
    engine.Sync(new(User))
    
    // Create a sample user
    engine.Insert(&User{Id: 1, Name: "user1"})
    

    The corrected code would look something as follows:

    package main
    
    import (
        "github.com/go-xorm/xorm"
        _ "github.com/go-sql-driver/mysql"
        xrc "github.com/go-xorm/xorm-redis-cache"
    
        "encoding/gob"
    )
    
    type User struct {
        Id   int `xorm:"pk"`
        Name string
    }
    
    func main() {
        gob.Register(new(User))
    
        engine, err := xorm.NewEngine("mysql", "root:@/xorm_test_db")
        if nil != err {
            log.Fatal(err)
        }
        engine.ShowSQL(true)
    
        cacher := xrc.NewRedisCacher("localhost:6379", "", xrc.DEFAULT_EXPIRATION, engine.Logger())
        engine.SetDefaultCacher(cacher)
    
        engine.Get(User{Id: 1})
        engine.Get(User{Id: 1})
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料