Created
September 5, 2015 11:34
-
-
Save himulawang/c3b0559115a29106a0a3 to your computer and use it in GitHub Desktop.
Go connect to non-cluster redis & mysql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"time" | |
log "github.com/Sirupsen/logrus" | |
"github.com/fzzy/radix/redis" | |
"github.com/fzzy/radix/extra/pool" | |
"github.com/jinzhu/gorm" | |
_ "github.com/go-sql-driver/mysql" | |
) | |
var DB gorm.DB | |
var RedisPool *pool.Pool | |
func main() { | |
initDB() | |
initRedis() | |
} | |
func initDB() { | |
db, err := gorm.Open("mysql", "root:123@tcp(192.168.1.7:53306)/meta?charset=utf8&parseTime=True&loc=Local") | |
if err != nil { | |
log.Errorln("Connect mysql failed", err) | |
time.Sleep(time.Second * 3) | |
initDB() | |
return | |
} | |
db.SingularTable(true) | |
db.LogMode(true) | |
db.DB().SetMaxIdleConns(10) | |
db.DB().SetMaxOpenConns(100) | |
DB = db | |
} | |
func initRedis() { | |
p, err := pool.NewCustomPool("tcp", "127.0.0.1:6379", 10, dialFunc) | |
if err != nil { | |
log.Errorln("Init redis pool failed", err) | |
time.Sleep(time.Second * 3) | |
initRedis() | |
return | |
} | |
log.Debugln("Init redis pool success") | |
RedisPool = p | |
} | |
func dialFunc(network, addr string) (*redis.Client, error) { | |
client, err := redis.Dial(network, addr) | |
if err != nil { | |
return nil, err | |
} | |
return client, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment