Created
December 13, 2014 20:50
-
-
Save murphysean/0da8d0c4633b1c29998c to your computer and use it in GitHub Desktop.
Redis Importer
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 ( | |
"flag" | |
"github.com/garyburd/redigo/redis" | |
"io/ioutil" | |
"log" | |
"time" | |
) | |
func newPool(server, password string) *redis.Pool { | |
return &redis.Pool{ | |
MaxIdle: 3, | |
IdleTimeout: 240 * time.Second, | |
Dial: func() (redis.Conn, error) { | |
c, err := redis.Dial("tcp", server) | |
if err != nil { | |
return nil, err | |
} | |
if password != "" { | |
if _, err := c.Do("AUTH", password); err != nil { | |
c.Close() | |
return nil, err | |
} | |
} | |
return c, err | |
}, | |
TestOnBorrow: func(c redis.Conn, t time.Time) error { | |
_, err := c.Do("PING") | |
return err | |
}, | |
} | |
} | |
var pool *redis.Pool | |
var dbHost string | |
var dbPass string | |
var key string | |
var jsonPath string | |
func init() { | |
flag.StringVar(&key, "key", "", "Specify the key to import the json to") | |
flag.StringVar(&jsonPath, "jsonPath", "", "Specify the json policy to import to redis") | |
flag.StringVar(&dbHost, "dbHost", "localhost:6379", "Specify the host:port to the redis db, default port is 6379") | |
flag.StringVar(&dbPass, "dbPass", "", "Specify the password to connect to the database") | |
} | |
func main() { | |
flag.Parse() | |
if jsonPath == "" || key == "" { | |
log.Println("Type -h for usage help") | |
return | |
} | |
c, err := redis.Dial("tcp", dbHost) | |
if err != nil { | |
log.Fatal(err) | |
return | |
} else { | |
log.Println("Connected to Redis DB @ ", dbHost) | |
c.Close() | |
pool = newPool(dbHost, dbPass) | |
log.Println("Creating Redis DB Connection Pool") | |
} | |
conn := pool.Get() | |
defer conn.Close() | |
bytes, err := ioutil.ReadFile(jsonPath) | |
if err != nil { | |
log.Fatal(err) | |
} | |
_, err = conn.Do("SET", key, string(bytes)) | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Println("Success!") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment