WH01243 преди 4 години
родител
ревизия
ce8f33cead

+ 1 - 1
entity/activity.go

@@ -8,7 +8,6 @@ import (
 //定义orm引擎
 var Engine *xorm.Engine
 
-
 //定义返回状态
 const (
 	SuccessCode int64 = 1
@@ -61,6 +60,7 @@ type UserPrize struct {
 	Id            int64     `xorm:"pk autoincr id" form:"id" json:"id"`
 	PrizeId       int64     `xorm:"prizeId" form:"prizeId" json:"prizeId"`                   //奖品Id
 	UserId        string    `xorm:"userId" form:"userId" json:"userId"`                      //用户标识
+	UserName      string    `xorm:"userName" form:"userName" json:"userName"`                //用户名称
 	ValidityDates int       `xorm:"validityDates" form:"validityDates" json:"validityDates"` //有效天数
 	BeginDate     string    `xorm:"beginDate" form:"beginDate" json:"beginDate"`             //有效期起
 	EndDate       string    `xorm:"endDate" form:"endDate" json:"endDate"`                   //有效期止

+ 11 - 12
rpc/activity.go

@@ -24,35 +24,34 @@ import (
 )
 
 var configFile = flag.String("f", "etc/activity.yaml", "the config file")
-var c config.Config
+
 func main() {
 	flag.Parse()
-	conf.MustLoad(*configFile, &c)
-	ctx := svc.NewServiceContext(c)
+	conf.MustLoad(*configFile, &config.ConfigJson)
+	ctx := svc.NewServiceContext(config.ConfigJson)
 	srv := server.NewActivityServer(ctx)
-	s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
+	s := zrpc.MustNewServer(config.ConfigJson.RpcServerConf, func(grpcServer *grpc.Server) {
 		activity.RegisterActivityServer(grpcServer, srv)
 	})
+	s.AddUnaryInterceptors(rateLimitInterceptor)
 	defer s.Stop()
 	b := cron.New()
-	b.AddFunc(c.TimeSource, timeDask)
+	b.AddFunc(config.ConfigJson.TimeSource, timeDask)
 	b.Start()
-	timeDask()
-	fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
+	fmt.Printf("Starting rpc server at %s...\n", config.ConfigJson.ListenOn)
 	s.Start()
 }
 //创建orm引擎
 func init() {
 	var err error
-	conf.MustLoad(*configFile, &c)
-	entity.Engine, err = xorm.NewEngine("mysql", c.DataSource)
+	entity.Engine, err = xorm.NewEngine("mysql", config.ConfigJson.DataSource)
 	entity.Engine.ShowSQL(true)
 	if err != nil {
 		log.Fatal("数据库连接失败:", err)
 	}
-	fmt.Println(c.DataSource+"链接成功")
+	fmt.Println(config.ConfigJson.DataSource+"链接成功")
 
-	redisCfg := c.Redis
+	redisCfg := config.ConfigJson.Redis
 	if redisCfg.Addr != "" {
 		e := util.InitRedisPool(redisCfg.Modules, redisCfg.Addr, redisCfg.PoolMaxSize, redisCfg.PoolMaxIdle, redisCfg.IdleTimeout)
 		if e == nil {
@@ -82,7 +81,7 @@ func rateLimitInterceptor(ctx context.Context, req interface{}, info *grpc.Unary
 		eqspStr=eqspStr[0:300]
 	}
 	var sqlerr error
-	_,sqlerr = orm.Exec("INSERT INTO `interface_log`(`interName`, `calleeId`, `appId`, `inParameter`, `reTurnInfo`, `node`, `summary`,timestamp) VALUES (?,?,?,?,?,?,?,now())",info.FullMethod,c.CalleeId,appId,jsonStr,eqspStr,c.Node,"")
+	_,sqlerr = orm.Exec("INSERT INTO `interface_log`(`interName`, `calleeId`, `appId`, `inParameter`, `reTurnInfo`, `node`, `summary`,timestamp) VALUES (?,?,?,?,?,?,?,now())",info.FullMethod,config.ConfigJson.CalleeId,appId,jsonStr,eqspStr,config.ConfigJson.Node,"")
 	if sqlerr != nil {
 		log.Print("日志存储失败", sqlerr)
 	}

+ 3 - 1
rpc/activity.proto

@@ -5,15 +5,17 @@ package activity;
 message Request {
   int64 activityId= 1;//活动标识
   string userId=2;//用户标识
-  string AppId=3;//身份标识
+  string appId=3;//身份标识
   int64  Page=4;
   int64  PageSize=5;
   int64  model=6;//1查看名下所有奖券 0查看可以使用的奖券(没有过期的)
+  string userName=7//用户名称
 }
 message LotteryOperation{
    repeated int64 lotteryIdArr=1;//奖券标识集合
    string userId=2;//用户标识
    string AppId=3;//身份标识
+   string UserName=4;//用户名称
 }
 
 

+ 2 - 0
rpc/etc/activity.yaml

@@ -9,6 +9,7 @@ Redis:
   idleTimeout: 240
   maxSize: 20
   maxIdle: 20
+  idleTimeOut: 240
 Etcd:
   Hosts:
   - 127.0.0.1:2379
@@ -19,6 +20,7 @@ FileSystemConf:
     Hosts:
       - 127.0.0.1:2379
     Key: activity.rpc
+
 CalleeId: activity.rpc
 Node: 1
 TimeSource: 0 1 0 * * ? *

+ 2 - 0
rpc/internal/config/config.go

@@ -11,6 +11,8 @@ type Config struct {
 	TimeSource     string //定时任务
 	Redis          Redis
 }
+
+var  ConfigJson Config
 type Redis struct {
 	Addr        string `json:"addr"`
 	Modules     string `json:"modules"`

+ 1 - 1
rpc/internal/logic/lotteryreceivelogic.go

@@ -32,7 +32,7 @@ func NewLotteryReceiveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Lo
 func (l *LotteryReceiveLogic) LotteryReceive(in *activity.LotteryOperation) (*activity.Response, error) {
 	// todo: add your logic here and delete this line
 	result := &activity.Response{}
-	code, msg := activityService.LotteryReceive(in)
+	code, msg := activityService.LotteryReceive(in,"other")
 	result.Code =code
 	result.Message = msg
 	return result, nil

+ 1 - 1
rpc/internal/logic/userlotterylogic.go

@@ -44,7 +44,7 @@ func (l *UserLotteryLogic) UserLottery(in *activity.Request) (*activity.Activity
 	fmt.Println(count)
 	result.Code = code
 	result.Message = msg
-	///result.Count=count
+	result.Count=count
 	result.Data = userLotteryList
 	return &activity.ActivityLotteryResp{}, nil
 }

+ 13 - 1
rpc/test/activity.yaml

@@ -1,5 +1,15 @@
 Name: activity.rpc
 ListenOn: 127.0.0.1:8080
+Redis:
+  Host: 127.0.0.1
+  addr: 127.0.0.1:6379
+  modules:  activity
+  poolMaxSize: 10
+  poolMaxIdle: 20
+  idleTimeout: 240
+  maxSize: 20
+  maxIdle: 20
+  idleTimeOut: 240
 Etcd:
   Hosts:
     - 127.0.0.1:2379
@@ -11,4 +21,6 @@ FileSystemConf:
       - 127.0.0.1:2379
     Key: activity.rpc
 CalleeId: activity.rpc
-Node: 1
+Node: 1
+TimeSource: 0 1 0 * * ? *
+

+ 15 - 2
service/ActivityService.go

@@ -3,6 +3,7 @@ package service
 import (
 	"app.yhyue.com/moapp/jyMarketing/entity"
 	"app.yhyue.com/moapp/jyMarketing/rpc/activity"
+	"app.yhyue.com/moapp/jyMarketing/util"
 	"fmt"
 	_ "github.com/garyburd/redigo/redis"
 	"log"
@@ -12,7 +13,7 @@ import (
 type ActivityService struct{}
 
 //奖券获取
-func (service *ActivityService) LotteryReceive(data *activity.LotteryOperation) (int64, string) {
+func (service *ActivityService) LotteryReceive(data *activity.LotteryOperation,code string) (int64, string) {
 	orm := entity.Engine.NewSession()
 	defer orm.Close()
 	err := orm.Begin()
@@ -21,6 +22,10 @@ func (service *ActivityService) LotteryReceive(data *activity.LotteryOperation)
 		return entity.ErrorCode, "没有卷可以领取"
 	}
 	for _, lotteryId := range data.LotteryIdArr {
+		if  fool,_:=util.Exists(code,"lottery_"+fmt.Sprint(lotteryId)); !fool{
+			orm.Rollback()
+			return entity.ErrorCode, "奖卷领取失败"
+		}
 		log.Println(fmt.Sprint(lotteryId) + "Id奖券领取")
 		//每种劵处理
 		//1、先查询奖券信息
@@ -55,7 +60,6 @@ func (service *ActivityService) LotteryReceive(data *activity.LotteryOperation)
 				return entity.ErrorCode, "你领取奖券数量已达上限"
 			}
 		}
-		//3、在判断奖券是否够用
 		//4、领取奖券
 		userLettry := entity.UserPrize{}
 		userLettry.AppId = data.AppId
@@ -68,6 +72,7 @@ func (service *ActivityService) LotteryReceive(data *activity.LotteryOperation)
 		userLettry.Name = prizeData.Name
 		userLettry.Full = int64(prizeData.Full)
 		userLettry.Reduce = int64(prizeData.Reduce)
+		//userLettry.UserName=data.
 		//0、有起止时间1、当天起几天可用2、次日起几天可用
 		switch prizeData.ValidityTimeType {
 		case 0:
@@ -99,6 +104,14 @@ func (service *ActivityService) LotteryReceive(data *activity.LotteryOperation)
 			orm.Rollback()
 			return entity.ErrorCode, "修改奖券库存失败"
 		}
+		//6、修改redis余额
+		if !util.DecrbyLimit(code,"lottery_"+fmt.Sprint(lotteryId),1,0){
+			log.Panicln("修改redis奖券库存失败:", err)
+			orm.Rollback()
+
+			return entity.ErrorCode, "修改redis奖券库存失败"
+		}
+
 
 	}
 	orm.Commit()

+ 38 - 1
util/redis.go

@@ -211,7 +211,44 @@ func GetInterface(code, key string, result interface{}) {
 		}
 	}
 }
-
+//增加多少数据
+func Incrby(code, key string, val int) int64 {
+	defer catch()
+	conn := RedisPool[code].Get()
+	defer conn.Close()
+	ret, err := conn.Do("INCRBY", key, val)
+	if nil != err {
+		log.Println("redisutil-INCRBY-Error", err)
+	} else {
+		if res, ok := ret.(int64); ok {
+			return res
+		} else {
+			return 0
+		}
+	}
+	return 0
+}
+//自减(带限制的)
+func DecrbyLimit(code, key string, val int, limit int64) bool {
+	defer catch()
+	conn := RedisPool[code].Get()
+	defer conn.Close()
+	ret, err := conn.Do("DECRBY", key, val)
+	if nil != err {
+		log.Println("redisutil-DECR-Error", err)
+		return false
+	} else {
+		if res, ok := ret.(int64); ok {
+			if res < limit {
+				Incrby(code, key, val)
+				return false
+			}
+			return true
+		} else {
+			return false
+		}
+	}
+}
 //直接返回字节流
 func GetBytes(code, key string) (ret *[]byte, err error) {
 	defer catch()