Commit ab097e5d by yemin

日志增加格式化打印

redis增加锁、hash的操作 增加httpclient工具
parent f2767dca
...@@ -66,6 +66,10 @@ type RedisConf struct { ...@@ -66,6 +66,10 @@ type RedisConf struct {
RedisPort int RedisPort int
RedisPwd string RedisPwd string
RedisDb int RedisDb int
ReadTimeout int //取超时间 单位秒 默认值为3秒
WriteTimeout int // 写入超时时间 单位秒 默认与读超时时间一致
PoolSize int //最大连接数 默认cpu数*10
MinIdleConns int //最小空闲连接数
} }
var Redis = RedisConf{} var Redis = RedisConf{}
......
package httpclient
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
)
// HttpClient 本项目中使用的http客户端
var HttpClient *http.Client
func init() {
HttpClient = &http.Client{}
//HttpClient.Timeout = config.Conf.Http.Client.Timeout * time.Millisecond //设置请求超时时间
}
// Get get方法的http请求,返回原始字符串
func Get(url string) ([]byte, error) {
rep, err := HttpClient.Get(url)
if err != nil {
return nil, err
}
defer rep.Body.Close()
data, err := ioutil.ReadAll(rep.Body)
if err != nil {
return nil, err
}
return data, nil
}
// GetWithHeader get方法的http请求,返回原始字符串
func GetWithHeader(url string, header *map[string]string) ([]byte, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
//设置header
req.Header.Set("Content-Type", "application/json;charset=UTF-8")
if header != nil {
for k, v := range *header {
req.Header.Set(k, v)
}
}
//发送请求
rep, err := HttpClient.Do(req)
if err != nil {
return nil, err
}
defer rep.Body.Close()
//处理返回值
data, err := ioutil.ReadAll(rep.Body)
if err != nil {
return nil, err
}
return data, nil
}
// Post post请求,json
// url 请求地址
// header header参数
// badyParam body参数
func Post(url string, header *map[string]string, badyParam *interface{}) ([]byte, error) {
//处理body参数
var bt []byte
if badyParam != nil {
b, err := json.Marshal(*badyParam)
if err != nil {
return nil, err
}
bt = b
}
//创建post请求
req, err := http.NewRequest("POST", url, bytes.NewReader(bt))
if err != nil {
return nil, err
}
//设置header
req.Header.Set("Content-Type", "application/json;charset=UTF-8")
if header != nil {
for k, v := range *header {
req.Header.Set(k, v)
}
}
//发送请求
rep, err := HttpClient.Do(req)
if err != nil {
return nil, err
}
defer rep.Body.Close()
//处理返回值
data, err := ioutil.ReadAll(rep.Body)
if err != nil {
return nil, err
}
return data, nil
}
...@@ -33,7 +33,11 @@ func IsDebug() bool { ...@@ -33,7 +33,11 @@ func IsDebug() bool {
return ok return ok
} }
func Debug(msg string) { func Debugf(format string, msg ...interface{}) {
Debug(fmt.Sprintf(format, msg...))
}
func Debug(msg interface{}) {
ok := false ok := false
switch strings.ToLower(conf.LogLevel) { switch strings.ToLower(conf.LogLevel) {
case strings.ToLower(LevelDebug): case strings.ToLower(LevelDebug):
...@@ -42,11 +46,15 @@ func Debug(msg string) { ...@@ -42,11 +46,15 @@ func Debug(msg string) {
} }
if ok { if ok {
_, file, line, _ := runtime.Caller(1) _, file, line, _ := runtime.Caller(1)
print(LevelDebug, msg, file, line) print(LevelDebug, file, line, msg)
} }
} }
func Info(msg string) { func Infof(format string, msg ...interface{}) {
Info(fmt.Sprintf(format, msg...))
}
func Info(msg interface{}) {
ok := false ok := false
switch strings.ToLower(conf.LogLevel) { switch strings.ToLower(conf.LogLevel) {
case strings.ToLower(LevelDebug): case strings.ToLower(LevelDebug):
...@@ -58,11 +66,15 @@ func Info(msg string) { ...@@ -58,11 +66,15 @@ func Info(msg string) {
} }
if ok { if ok {
_, file, line, _ := runtime.Caller(1) _, file, line, _ := runtime.Caller(1)
print(LevelInfo, msg, file, line) print(LevelInfo, file, line, msg)
} }
} }
func Warn(msg string) { func Warnf(format string, msg ...interface{}) {
Warn(fmt.Sprintf(format, msg...))
}
func Warn(msg interface{}) {
ok := false ok := false
switch strings.ToLower(conf.LogLevel) { switch strings.ToLower(conf.LogLevel) {
case strings.ToLower(LevelDebug): case strings.ToLower(LevelDebug):
...@@ -77,11 +89,15 @@ func Warn(msg string) { ...@@ -77,11 +89,15 @@ func Warn(msg string) {
} }
if ok { if ok {
_, file, line, _ := runtime.Caller(1) _, file, line, _ := runtime.Caller(1)
print(LevelWarn, msg, file, line) print(LevelWarn,file, line, msg)
} }
} }
func Error(msg string) { func Errorf(format string, msg ...interface{}) {
Error(fmt.Sprintf(format, msg...))
}
func Error(msg interface{}) {
ok := false ok := false
switch strings.ToLower(conf.LogLevel) { switch strings.ToLower(conf.LogLevel) {
case strings.ToLower(LevelDebug): case strings.ToLower(LevelDebug):
...@@ -99,7 +115,7 @@ func Error(msg string) { ...@@ -99,7 +115,7 @@ func Error(msg string) {
} }
if ok { if ok {
_, file, line, _ := runtime.Caller(1) _, file, line, _ := runtime.Caller(1)
print(LevelError, msg, file, line) print(LevelError, file, line, msg)
} }
} }
...@@ -119,7 +135,7 @@ const ( ...@@ -119,7 +135,7 @@ const (
yellowBold = "\033[33;1m" yellowBold = "\033[33;1m"
) )
func print(tag, msg string, file string, line int) { func print(tag, file string, line int, msg interface{}) {
str := "%s %s [%d] %s %d %s" str := "%s %s [%d] %s %d %s"
if conf.LogColorful { if conf.LogColorful {
switch tag { switch tag {
......
...@@ -20,6 +20,10 @@ func Init() { ...@@ -20,6 +20,10 @@ func Init() {
Addr: fmt.Sprintf("%s:%d", conf.Redis.RedisHost, conf.Redis.RedisPort), Addr: fmt.Sprintf("%s:%d", conf.Redis.RedisHost, conf.Redis.RedisPort),
Password: conf.Redis.RedisPwd, Password: conf.Redis.RedisPwd,
DB: conf.Redis.RedisDb, // redis一共16个库,指定其中一个库即可 DB: conf.Redis.RedisDb, // redis一共16个库,指定其中一个库即可
PoolSize: conf.Redis.PoolSize, //最大连接数 默认cpu数*10
MinIdleConns: conf.Redis.MinIdleConns, //最小空闲连接数
ReadTimeout: time.Duration(conf.Redis.ReadTimeout) * time.Second, //取超时间 单位秒 默认值为3秒
WriteTimeout: time.Duration(conf.Redis.WriteTimeout) * time.Second, // 写入超时时间 单位秒 默认与读超时时间一致
}) })
_, err := redisClient.Ping().Result() _, err := redisClient.Ping().Result()
if err != nil { if err != nil {
...@@ -75,9 +79,28 @@ func Get(key string) []byte { ...@@ -75,9 +79,28 @@ func Get(key string) []byte {
return rByte return rByte
} }
func Set(k string, v string) { func Set(k, v string) error {
getDb().Set(k, v, 0) e := getDb().Set(k, v, 0).Err()
if e==nil {
log.Debug(fmt.Sprintf("设置缓存成功:%s %s", k, v)) log.Debug(fmt.Sprintf("设置缓存成功:%s %s", k, v))
} else {
log.Debug(fmt.Sprintf("设置缓存失败:%s %s %s", k, v, e))
}
return e
}
func SetNx(k, v string, timeoutSecond int) error {
e := getDb().Set(k, v, time.Duration(timeoutSecond) * time.Second).Err()
if e==nil {
log.Debug(fmt.Sprintf("设置缓存成功:%s %s", k, v))
} else {
log.Debug(fmt.Sprintf("设置缓存失败:%s %s %s", k, v, e))
}
return e
}
func Del(ks ...string) (int64,error){
return getDb().Del(ks...).Result()
} }
func Expire(k string, t int64) bool { func Expire(k string, t int64) bool {
...@@ -90,3 +113,88 @@ func Expire(k string, t int64) bool { ...@@ -90,3 +113,88 @@ func Expire(k string, t int64) bool {
return b.Val() return b.Val()
} }
var lockScript string = `if redis.call("exists",KEYS[1]) == 0 then
local lockSrc = redis.call("setex",KEYS[1],unpack(ARGV))
if lockSrc then
return "1"
end
return "0"
end`
var unlockScript string = `if redis.call('get', KEYS[1]) == ARGV[1] then
local lockSrc = redis.call('del', KEYS[1])
if lockSrc then
return "1"
end
return "0"
end`
// Lock 抢锁。抢到锁返回true,否则false。只抢一次
// 所有参数必传,超时时间单位秒
func Lock(k, uniqueValue string, timeoutSecond int) bool {
r,_ := getDb().Eval(lockScript, []string{k}, timeoutSecond, uniqueValue).String()
if r=="1" {
return true
}
return false
}
// Unlock 解锁
// 所有参数必传
func Unlock(k, uniqueValue string) bool {
r,_ := getDb().Eval(unlockScript, []string{k}, uniqueValue).String()
if r=="1" {
return true
}
return false
}
// Hset 向一张hash表中放入数据,如果不存在将创建
func Hset(k, i, v string, timeoutSecond int) error {
e := getDb().HSet(k, i, v).Err()
if e==nil {
log.Debug(fmt.Sprintf("设置缓存成功:%s %s %s", k, i, v))
if timeoutSecond >0 {
Expire(k, int64(timeoutSecond))
}
} else {
log.Debug(fmt.Sprintf("设置缓存失败:%s %s %s %s", k, i, v, e))
}
return e
}
// HGet 从hash中获取值
func HGet(k, i string) (string,error) {
r,e := getDb().HGet(k,i).Result()
return r,e
}
// HGetAll 从hash中获key所有的取值
func HGetAll(k string) (map[string]string,error) {
return getDb().HGetAll(k).Result()
}
// Hdel 从hash中删除
func Hdel(k string, is ...string) (int64,error) {
r,e := getDb().HDel(k, is...).Result()
return r,e
}
// HMSet 向一张hash表中放入数据,如果不存在将创建
func HMSet(k string, fields map[string]interface{}, timeoutSecond int) error {
e := getDb().HMSet(k, fields).Err()
if e==nil {
log.Debug(fmt.Sprintf("设置缓存成功:%s %s", k, fields))
if timeoutSecond >0 {
Expire(k, int64(timeoutSecond))
}
} else {
log.Debug(fmt.Sprintf("设置缓存失败:%s %s %s", k, fields, e))
}
return e
}
func HMget(k string, is ...string) ([]interface{},error) {
return getDb().HMGet(k, is...).Result()
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment