Commit aff676f1 by zhengqiuyun86

Merge remote-tracking branch 'origin/master'

parents ca24e506 b6be637a
...@@ -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{}
......
...@@ -38,7 +38,7 @@ func FailGetWay(c *gin.Context, state State, subCode, subMsg string) { ...@@ -38,7 +38,7 @@ func FailGetWay(c *gin.Context, state State, subCode, subMsg string) {
resp := responseSub(state, subCode, subMsg) resp := responseSub(state, subCode, subMsg)
c.JSON(http.StatusBadGateway, resp) c.JSON(http.StatusBadGateway, resp)
c.Abort() c.Abort()
logEnd(c, resp) LogEnd(c, resp)
} }
func FailAndMsg(c *gin.Context, subCode, subMsg string) { func FailAndMsg(c *gin.Context, subCode, subMsg string) {
...@@ -46,32 +46,58 @@ func FailAndMsg(c *gin.Context, subCode, subMsg string) { ...@@ -46,32 +46,58 @@ func FailAndMsg(c *gin.Context, subCode, subMsg string) {
resp := ServerResponse{Code: BusinessError, Msg: "业务错误", SubCode: subCode, SubMsg: subMsg} resp := ServerResponse{Code: BusinessError, Msg: "业务错误", SubCode: subCode, SubMsg: subMsg}
c.JSON(http.StatusOK, resp) c.JSON(http.StatusOK, resp)
c.Abort() c.Abort()
logEnd(c, resp) LogEnd(c, resp)
} }
// FailAndMsgNoTx 不带事务
func FailAndMsgNoTx(c *gin.Context, subCode, subMsg string) {
resp := ServerResponse{Code: BusinessError, Msg: "业务错误", SubCode: subCode, SubMsg: subMsg}
c.JSON(http.StatusOK, resp)
c.Abort()
LogEnd(c, resp)
}
// Success 有事务的用这个
func Success(c *gin.Context) { func Success(c *gin.Context) {
db.Commit() db.Commit()
resp := response(OK) resp := response(OK)
c.JSON(http.StatusOK, resp) c.JSON(http.StatusOK, resp)
c.Abort() c.Abort()
logEnd(c, resp) LogEnd(c, resp)
} }
// SuccessNoTx 不带事务提交
func SuccessNoTx(c *gin.Context) {
resp := response(OK)
c.JSON(http.StatusOK, resp)
c.Abort()
LogEnd(c, resp)
}
// SuccessData 有事务的用这个
func SuccessData(c *gin.Context, data interface{}) { func SuccessData(c *gin.Context, data interface{}) {
db.Commit() db.Commit()
resp := ServerDataResponse{response(OK), data} resp := ServerDataResponse{response(OK), data}
c.JSON(http.StatusOK, resp) c.JSON(http.StatusOK, resp)
c.Abort() c.Abort()
logEnd(c, resp) LogEnd(c, resp)
}
// SuccessDataNoTx 不带事务提交
func SuccessDataNoTx(c *gin.Context, data interface{}) {
resp := ServerDataResponse{response(OK), data}
c.JSON(http.StatusOK, resp)
c.Abort()
LogEnd(c, resp)
} }
func SuccessString(c *gin.Context, data string) { func SuccessString(c *gin.Context, data string) {
c.String(http.StatusOK, data) c.String(http.StatusOK, data)
c.Abort() c.Abort()
logEnd(c, data) LogEnd(c, data)
} }
func logEnd(c *gin.Context, data interface{}) { func LogEnd(c *gin.Context, data interface{}) {
esSwitch := redis.SwitchOpen(redis.ES日志开关 + conf.ServerName) esSwitch := redis.SwitchOpen(redis.ES日志开关 + conf.ServerName)
startTime := GetStartTime(c) startTime := GetStartTime(c)
endTime := time.Now().UnixNano() endTime := time.Now().UnixNano()
......
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,7 @@ func IsDebug() bool { ...@@ -33,7 +33,7 @@ func IsDebug() bool {
return ok return ok
} }
func Debug(msg string) { func Debugf(format string, 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 +42,56 @@ func Debug(msg string) { ...@@ -42,11 +42,56 @@ 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, fmt.Sprintf(format, msg...))
} }
} }
func Info(msg string) { func Debug(msg interface{}) {
ok := false
switch strings.ToLower(conf.LogLevel) {
case strings.ToLower(LevelDebug):
ok = true
break
}
if ok {
_, file, line, _ := runtime.Caller(1)
print(LevelDebug, file, line, msg)
}
}
func Infof(format string, msg ...interface{}) {
ok := false
switch strings.ToLower(conf.LogLevel) {
case strings.ToLower(LevelDebug):
ok = true
break
case strings.ToLower(LevelInfo):
ok = true
break
}
if ok {
_, file, line, _ := runtime.Caller(1)
print(LevelInfo, file, line, fmt.Sprintf(format, msg...))
}
}
func Info(msg interface{}) {
ok := false
switch strings.ToLower(conf.LogLevel) {
case strings.ToLower(LevelDebug):
ok = true
break
case strings.ToLower(LevelInfo):
ok = true
break
}
if ok {
_, file, line, _ := runtime.Caller(1)
print(LevelInfo, file, line, msg)
}
}
func Warnf(format string, msg ...interface{}) {
ok := false ok := false
switch strings.ToLower(conf.LogLevel) { switch strings.ToLower(conf.LogLevel) {
case strings.ToLower(LevelDebug): case strings.ToLower(LevelDebug):
...@@ -55,14 +100,17 @@ func Info(msg string) { ...@@ -55,14 +100,17 @@ func Info(msg string) {
case strings.ToLower(LevelInfo): case strings.ToLower(LevelInfo):
ok = true ok = true
break break
case strings.ToLower(LevelWarn):
ok = true
break
} }
if ok { if ok {
_, file, line, _ := runtime.Caller(1) _, file, line, _ := runtime.Caller(1)
print(LevelInfo, msg, file, line) print(LevelWarn, file, line, fmt.Sprintf(format, msg...))
} }
} }
func Warn(msg string) { 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 +125,33 @@ func Warn(msg string) { ...@@ -77,11 +125,33 @@ 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 Errorf(format string, msg ...interface{}) {
ok := false
switch strings.ToLower(conf.LogLevel) {
case strings.ToLower(LevelDebug):
ok = true
break
case strings.ToLower(LevelInfo):
ok = true
break
case strings.ToLower(LevelWarn):
ok = true
break
case strings.ToLower(LevelError):
ok = true
break
}
if ok {
_, file, line, _ := runtime.Caller(1)
print(LevelError, file, line, fmt.Sprintf(format, msg...))
} }
} }
func Error(msg string) { 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 +169,7 @@ func Error(msg string) { ...@@ -99,7 +169,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 +189,7 @@ const ( ...@@ -119,7 +189,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