12
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RevelでGORMを使ってみる+SQLの返却データをCacheしてみようの巻

Last updated at Posted at 2014-11-26

Golangの有名なフレームワークのひとつRevelに用いるORMを探していたときにGorpを見つけたけれど、何となく違うなーと思って他を探していたときに見つけたORMのGorm

初期設定にハマったので備忘として。
せっかくなのでDBから取得したデータはRevelのCache機能でCacheするようにしてみた。

まずは gorm.go を作成。

package db

import (
	"github.com/revel/revel"
	"github.com/jinzhu/gorm"
    _ "github.com/go-sql-driver/mysql"
    "strings"
    "fmt"
    "time"
)

var Gdb gorm.DB
var GCacheTime time.Duration
var TimeFormat string

func getConnectionString() string {
    host := getParamString("db.host", "")
    port := getParamString("db.port", "3306")
    user := getParamString("db.user", "")
    pass := getParamString("db.password", "")
    dbname := getParamString("db.name", "")
    protocol := getParamString("db.protocol", "tcp")
    dbargs := getParamString("db.args", " ")

    if strings.Trim(dbargs, " ") != "" {
        dbargs = "?" + dbargs
    } else {
        dbargs = ""
    }
    return fmt.Sprintf("%s:%s@%s([%s]:%s)/%s%s", 
        user, pass, protocol, host, port, dbname, dbargs)
}

func InitDB() {
	var err error
    connectionString := getConnectionString()
    Gdb, err = gorm.Open("mysql", connectionString)
    if err != nil {
        revel.ERROR.Println("FATAL", err)
        panic( err )
    }
    Gdb.LogMode(getParamBool("db.debug"))
    GCacheTime = getCacheTime()
    TimeFormat = "2006-01-02 15:04:06"
}

func getParamString(param string, defaultValue string) string {
    p, found := revel.Config.String(param)
    if !found {
        if defaultValue == "" {
            revel.ERROR.Fatal("Cound not find parameter: " + param)
        } else {
            return defaultValue
        }
    }
    return p
}

func getParamInt(param string) int {
    p, found := revel.Config.Int(param)
    if !found {
        revel.ERROR.Fatal("Cound not find parameter: " + param)
    }
    return p
}

func getParamBool(param string) bool {
    p, found := revel.Config.Bool(param)
    if !found {
        revel.ERROR.Fatal("Cound not find parameter: " + param)
    }
    return p
}

func getCacheTime() time.Duration {
	cacheTime := time.Duration(getParamInt("cache.time")) * time.Minute
	if cacheTime < 0 {
		cacheTime = 1 * time.Nanosecond
	}
	return cacheTime
}

そしたら 今度は model を作成

package models

import (
	d "api.gamefeat.net/app/libs/db"
	"github.com/revel/revel/cache"
	"github.com/revel/revel"
	"errors"
)

func (t TableModel) FindData(id string) (res TableModel, err error){
	//DB接続
	d.InitDB()	
	if c := cache.Get("SQL_CACHE_"+id, &res); c != nil {
		if d.Gdb.Table("table_name").Select("*").Where("id = ?", id, 0, 0).First(&res).RecordNotFound() {
			err = errors.New("FindData - NoData id : "+id)
			return res, err
		}
		
		go cache.Set("SQL_CACHE_"+id, res, d.GCacheTime)
	}
	
	revel.INFO.Println(d.GCacheTime)
	revel.INFO.Println(res)
	return res, err
}

これでとりあえずGORMを使えるようになるはず。
GORMはなかなか便利で使い勝手がいい感じがした。

12
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?