Browse Source

添加计数器功能

zhanghongbo 9 năm trước cách đây
mục cha
commit
9450d8bb77

+ 28 - 0
common/src/qfw/util/redis/redisutil.go

@@ -386,3 +386,31 @@ func DelByPattern(key string) {
 
 }
 **/
+//自增计数器
+func Incr(code, key string) int64 {
+	defer func() {
+		if r := recover(); r != nil {
+			log.Println("[E]", r)
+			for skip := 1; ; skip++ {
+				_, file, line, ok := runtime.Caller(skip)
+				if !ok {
+					break
+				}
+				go log.Printf("%v,%v\n", file, line)
+			}
+		}
+	}()
+	conn := RedisPool[code].Get()
+	defer conn.Close()
+	ret, err := conn.Do("INCR", key)
+	if nil != err {
+		log.Println("redisutil-GetError", err)
+	} else {
+		if res, ok := ret.(int64); ok {
+			return res
+		} else {
+			return 0
+		}
+	}
+	return 0
+}

+ 5 - 0
common/src/qfw/util/redis/redisutil_test.go

@@ -56,3 +56,8 @@ func Test_other(t *testing.T) {
 	}
 	<-pools
 }
+
+func TestIncr(t *testing.T) {
+	InitRedis("sso=192.168.3.14:1379")
+	log.Println(Incr("sso", "user"))
+}

+ 22 - 0
core/src/qfw/coreutil/counterutil.go

@@ -0,0 +1,22 @@
+package coreutil
+
+import (
+	"qfw/util/redis"
+)
+
+//计数器
+const (
+	TYPE_INVITE = iota //邀请
+	TYPE_GIVE          //赠送积分
+)
+
+//基于Redis的计数器实现
+func GetShareId(businesstype int) uint32 {
+	var tmp int64
+	if businesstype == TYPE_INVITE {
+		tmp = redis.Incr("other", "invite_counter") + 3200000000
+	} else if businesstype == TYPE_GIVE {
+		tmp = redis.Incr("other", "give_counter") + 3200000000
+	}
+	return uint32(tmp)
+}

+ 13 - 0
core/src/qfw/coreutil/counterutil_test.go

@@ -0,0 +1,13 @@
+package coreutil
+
+import (
+	"log"
+	"qfw/util/redis"
+	"testing"
+)
+
+func TestCounter(t *testing.T) {
+	redis.InitRedis("other=192.168.3.14:1379")
+	log.Println("初始化缓存")
+	log.Println("id::", GetShareId(TYPE_INVITE))
+}

+ 4 - 4
weixin/src/qfw/weixin/rpc/share.go

@@ -2,10 +2,10 @@ package rpc
 
 import (
 	"encoding/json"
+	"fmt"
 	"github.com/SKatiyar/qr"
 	"log"
 	"qfw/util/redis"
-	"strconv"
 )
 
 /**生成分享二维码
@@ -13,14 +13,14 @@ import (
 	开发在使用时,先查看redis,没有的话再调用此RPC方法
 	生成的二维码有效期为一个月
 **/
-func (wxrpc *WeiXinRpc) GetShareQR(shareid int, ret *string) (err error) {
+func (wxrpc *WeiXinRpc) GetShareQR(shareid uint32, ret *string) (err error) {
 	//构造自定义消息文本
 	var msg struct {
 		Expire int    `json:"expire_seconds"`
 		Name   string `json:"action_name"`
 		Info   struct {
 			Scene struct {
-				Id int `json:"scene_id"`
+				Id uint32 `json:"scene_id"`
 			} `json:"scene"`
 		} `json:"action_info"`
 	}
@@ -40,7 +40,7 @@ func (wxrpc *WeiXinRpc) GetShareQR(shareid int, ret *string) (err error) {
 	r, _ := qr.Encode(url, qr.L)
 	pngdat := r.PNG()
 	//存储到redis
-	redis.PutBytes("sso", "p_share_"+strconv.Itoa(shareid), &pngdat, msg.Expire)
+	redis.PutBytes("sso", fmt.Sprintf("p_share_%d", shareid), &pngdat, msg.Expire)
 	*ret = "ok"
 	return nil
 }