go语言之行--golang操作redis、mysql大全
https://www.cnblogs.com/wdliu/p/9330278.html
http://www.topgoer.com/数据库操作/go操作redis/redis介绍.html
package main
import (
"bufio"
"fmt"
"github.com/garyburd/redigo/redis"
"os"
"time"
)
var RedisConn redis.Conn
func init() {
InitRedis()
}
func InitRedis() {
rConn, err := redis.Dial("tcp", "10.10.10.141:6379")
RedisConn = rConn
if err != nil {
fmt.Println("conn redis failed,", err)
return
}
//defer RedisConn.Close()
//连接密码
_, err = RedisConn.Do("Auth", "123456")
if err != nil {
fmt.Println(err)
return
}
fmt.Println("redis conn success")
}
func main() {
//testString()
testHash()
Log("log","main","22222")
}
func testString() {
_, err := RedisConn.Do("Set", "abc", 10333)
if err != nil {
fmt.Println(err)
return
}
r, err := redis.Int(RedisConn.Do("Get", "abc"))
if err != nil {
fmt.Println("get abc failed,", err)
return
}
fmt.Println(r)
}
func testHash() {
_, err := RedisConn.Do("HSet", "masscan","taskName", "123123")
if err != nil {
fmt.Println("redis HSet error:", err)
}
r, err := redis.String(RedisConn.Do("HGet", "masscan","taskName"))
if err != nil {
fmt.Println("redis HGet error:", err)
return
}
fmt.Println(r)
}
//DebugLog2 自定义日志文件
/*
* dir 文件夹名字
* fileName 文件名字
* args 要写入的数据
*/
func Log(dir string, fileName string, args ...interface{}) error {
var floderLog = "logs"
if fileName != "" {
floderLog = floderLog + "/" + dir
}
logName := floderLog + "/" + fileName + time.Now().Format("2006-01-02") + ".log"
if _, err := os.Stat(floderLog); err != nil {
if !os.IsExist(err) {
os.MkdirAll(floderLog, os.ModePerm)
}
}
logFile, err := os.OpenFile(logName, os.O_APPEND|os.O_RDWR|os.O_CREATE, os.ModePerm)
if err != nil {
fmt.Println("打开文件失败 err:", err)
return err
}
defer logFile.Close()
tm := time.Now().Format("2006-01-02 15:04:05")
//方法一:os包
// logBody := fmt.Sprintf("%s star============================================>\r\n", tm)
// logFile.WriteString(logBody)
// logBody = fmt.Sprintf("%+v\r\n", args)
// logFile.WriteString(logBody)
// logBody = fmt.Sprintf("\r\n")
// logFile.WriteString(logBody)
//方法二:bufio包
writer := bufio.NewWriter(logFile)
logBody := fmt.Sprintf("%s star============================================>\r\n", tm)
writer.WriteString(logBody) //写入缓存
logBody = fmt.Sprintf("%+v\r\n", args)
writer.WriteString(logBody)
logBody = fmt.Sprintf("\r\n")
writer.WriteString(logBody)
writer.Flush() //从缓存写入文件
return nil
}
[Haima的博客]
http://www.cnblogs.com/haima/