Initial commit

This commit is contained in:
Donny
2019-04-22 20:46:32 +08:00
commit 49ab8aadd1
25441 changed files with 4055000 additions and 0 deletions

View File

@@ -0,0 +1,38 @@
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [
":package-srcs",
"//app/interface/main/activity/cmd:all-srcs",
"//app/interface/main/activity/conf:all-srcs",
"//app/interface/main/activity/dao/bnj:all-srcs",
"//app/interface/main/activity/dao/bws:all-srcs",
"//app/interface/main/activity/dao/kfc:all-srcs",
"//app/interface/main/activity/dao/like:all-srcs",
"//app/interface/main/activity/dao/sports:all-srcs",
"//app/interface/main/activity/dao/timemachine:all-srcs",
"//app/interface/main/activity/http:all-srcs",
"//app/interface/main/activity/model/bnj:all-srcs",
"//app/interface/main/activity/model/bws:all-srcs",
"//app/interface/main/activity/model/kfc:all-srcs",
"//app/interface/main/activity/model/like:all-srcs",
"//app/interface/main/activity/model/sports:all-srcs",
"//app/interface/main/activity/model/timemachine:all-srcs",
"//app/interface/main/activity/rpc/client:all-srcs",
"//app/interface/main/activity/rpc/server:all-srcs",
"//app/interface/main/activity/service/bnj:all-srcs",
"//app/interface/main/activity/service/bws:all-srcs",
"//app/interface/main/activity/service/kfc:all-srcs",
"//app/interface/main/activity/service/like:all-srcs",
"//app/interface/main/activity/service/sports:all-srcs",
"//app/interface/main/activity/service/timemachine:all-srcs",
],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,405 @@
### activity-interface
#### Version 1.23.4
##### Features
> 1.bnj fail report
> 2.bnj timeline add like count
#### Version 1.23.3
##### Features
> 1.bnj reset fix
#### Version 1.23.2
##### Features
> 1.bnj reset return cd
> 2.bnj add timeline and admin check
#### Version 1.23.1
##### Features
> 1.article oid info.
#### Version 1.23.0
##### Features
> 1.bnj arc load in memory.
#### Version 1.22.2
##### Features
> 1.bnj name conf .
#### Version 1.22.1
##### Features
> 1.bnj kfc info .
#### Version 1.22.0
##### Features
> 1.bnj preview info add h5 fields.
#### Version 1.21.6
##### Features
> 1.fix time machine empty data.
#### Version 1.21.5
##### Features
> 1.fix time machine live hour.
#### Version 1.21.4
##### Features
> 1.fix panic.
#### Version 1.21.3
##### Features
> 1.fix no ugc data.
#### Version 1.21.2
##### Features
> 1.change time machine view sort rule.
#### Version 1.21.1
##### Features
> 1.bnj preview game cancel to job
> 2.time machine view sort fix
#### Version 1.21.0
##### Features
> 1.time machine
#### Version 1.20.6
##### Features
> 1.bnj preview add act id and sub id
#### Version 1.20.6
##### Features
> 1.bnj preview key add lid
#### Version 1.20.5
##### Features
> 1.kfc 券缓存回源
#### Version 1.20.4
##### Features
> 1.account接入grpc
#### Version 1.20.3
##### Features
> 1.kfc 回源逻辑
#### Version 1.20.2
##### Features
> 1.bnj preview add debug func.
> 2.bnj preview reset cd change.
#### Version 1.20.1
##### Features
> 1.bnj preview coupon fix.
#### Version 1.20.0
##### Features
> 1.bnj preview.
#### Version 1.19.3
##### Features
> 1.kfc发券优化
#### Version 1.19.2
##### Features
> 1.kfc发券核销
#### Version 1.19.1
##### Features
> 1.up主活动删除配置
#### Version 1.19.0
##### Features
> 1.禁封账号禁止点赞
#### Version 1.18.5
##### Features
> 1.like数据回源
#### Version 1.18.4
##### Features
> 1.up主点赞上线配置
#### Version 1.18.3
##### Features
> 1.列表接入随机排序
#### Version 1.18.2
##### Features
> 1.废除dao cache,替换成fanout
#### Version 1.18.1
##### Features
> 1.废除cache,替换成fanout
#### Version 1.18.0
##### Features
> 1.点赞列表不需要强校验登录态
#### Version 1.17.5
##### Features
> 1.ipv4ToIPv6
#### Version 1.17.4
##### Features
> 1.视频热度搜索接入es
#### Version 1.17.3
##### Features
> 1.初始化like_extend数据
#### Version 1.17.2
##### Features
> 1.提供act_subject And protocol数据
#### Version 1.17.1
##### Features
> 1.提供protocol表数据
#### Version 1.17.0
##### Features
> 1.新增获取故事王热度方法
#### Version 1.16.2
##### Features
> 1.object/group fatal err fix
#### Version 1.16.1
##### Features
> 1.新增 object/group warn log
#### Version 1.16.0
##### Features
> 1.新增 object/group 方法
#### Version 1.15.8
##### Features
> 1.故事王活动
#### Version 1.15.7
##### Features
> 1.fix mset error
#### Version 1.15.6
##### Features
> 1.add lottery
#### Version 1.15.5
##### Features
> 1.fix obj result
#### Version 1.15.4
##### Features
> 1.合并阅读数
#### Version 1.15.3
##### Features
> 1.add/guess 发挂件支持多个
> 2.match/guess/log result字段fix
#### Version 1.15.2
##### Features
> 1.add/guess 接口新增加抽奖次数逻辑
#### Version 1.15.1
##### Bug Fixes
> 1.match/guess/log game_stime字段fix
#### Version 1.15.0
##### Features
> 1.新增view/rank 相关接口
#### Version 1.14.0
##### Features
> 1.新增mission user 接口
#### Version 1.13.0
##### Features
> 1.新增act subject rpc 接口
> 2.match/guess/log 新增 game_stime 字段
#### Version 1.12.0
##### Features
> 1.迎新活动
#### Version 1.11.0
##### Features
> 1.新增竞猜日志
> 2.新增获取活动总点赞数据接口
#### Version 1.10.4
##### Features
> 1.fix log fmt.
#### Version 1.10.3
##### Features
> 1.rpcService fix
#### Version 1.10.2
##### Features
> 1.点赞接口接入go
#### Version 1.10.1
##### Features
> 1.使用metadata.remoteip
#### Version 1.10.0
##### Features
> 1.新增好乡音相关接口
#### Version 1.9.0
##### Features
> 1.新增red/dot接口
#### Version 1.8.0
##### Features
> 1.切换identity
#### Version 1.7.1
##### Features
> 1.抽奖接口支持day参数
#### Version 1.7.0
##### Features
> 1.key info 空缓存逻辑修改
#### Version 1.6.9
##### Features
> 1.key info 新增空缓存
#### Version 1.6.8
##### Features
> 1.修复游戏先失败后成功无法激活成就bug
#### Version 1.6.7
##### Features
> 1.全量数据回源去掉expire
#### Version 1.6.6
##### Features
> 1.user add key
#### Version 1.6.5
##### Features
> 1.binding lottery
> 2.add more log
#### Version 1.6.4
##### Features
> 1.游戏成就激活 fix
#### Version 1.6.3
##### Features
> 1.游戏成就激活bug fix
#### Version 1.6.2
##### Features
> 1.max hp 逻辑修改
#### Version 1.6.1
##### Features
> 1.key后绑定补发挂件
#### Version 1.6.0
##### Features
> 1.新增admin查询接口
#### Version 1.5.7
##### Features
> 1.新增奖池查询接口
> 2.add lottery mid check
#### Version 1.5.6
##### Features
> 1.fix user key panic
> 2.fix 加成就时award值
#### Version 1.5.5
##### Features
> 1.bws新增抽奖接口
> 2.成就完成个数区分日期
#### Version 1.5.4
##### Features
> 1.bws fix
#### Version 1.5.3
##### Features
> 1.bws 修改激活时type值
#### Version 1.5.2
##### Features
> 1.bws hp值fix
#### Version 1.5.1
##### Features
> 1.bws抽奖接口
#### Version 1.5.0
##### Features
> 1.bws活动接口
#### Version 1.4.8
##### Features
> 1.qq news fix
#### Version 1.4.7
##### Features
> 1.conf rule
> 2.add guess同步写缓存
#### Version 1.4.6
##### Features
> 1.coin reason
#### Version 1.4.5
##### Features
> 1.add log
#### Version 1.4.4
##### Features
> 1.比赛结果接口修改
#### Version 1.4.3
##### Features
> 1.新闻接口修改
#### Version 1.4.2
##### Features
> 1.球员排行榜修改
#### Version 1.4.1
##### Features
> 1.代码格式化
#### Version 1.4.0
##### Features
> 1.添加世界杯QQ接口
#### Version 1.3.2
##### Features
> 1.http use bm
#### Version 1.3.1
##### Features
> 1.迁移caster
##### Version 1.2.1
##### Features
> 1.log 修改
##### Version 1.2.0
##### Features
> 1.迁移main目录
##### Version 1.1.0
##### Features
> 1.删除 statsd
##### Version 1.1.0
##### Features
> 1.archive3 切换
##### Version 1.0.0
##### Features
> 1.初始化项目

View File

@@ -0,0 +1,13 @@
# Owner
liweijia
# Author
guanyanliang
wuhao02
laiying
# Reviewer
wuhao02
guanyanliang
liweijia
laiying

View File

@@ -0,0 +1,18 @@
# See the OWNERS docs at https://go.k8s.io/owners
approvers:
- guanyanliang
- laiying
- liweijia
- wuhao02
labels:
- interface
- interface/main/activity
- main
options:
no_parent_owners: true
reviewers:
- guanyanliang
- laiying
- liweijia
- wuhao02

View File

@@ -0,0 +1,15 @@
#### activity
##### 项目简介
> 1.活动相关高并发接口
##### 编译环境
> 请使用golang v1.7.x以上版本编译执行。
##### 依赖包
> 1.公共包go-common
##### 编译执行
> 在主目录执行go build。
> 编译后可执行 ./activity -conf activity-test.toml 使用项目本地配置文件启动服务。
> 也可执行 ./activity -conf_appid=activity -conf_version=v2.1.0 -conf_host=172.16.33.134:9011 -conf_path=/data/conf/activity -conf_env=10 -conf_token=SEHXM8x1vYhIUaZvQUmyWnMYJrF9jHJY 使用配置中心测试环境配置启动服务如无法启动可检查token是否正确。

View File

@@ -0,0 +1,45 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_binary",
"go_library",
)
go_binary(
name = "cmd",
embed = [":go_default_library"],
tags = ["automanaged"],
)
go_library(
name = "go_default_library",
srcs = ["main.go"],
data = ["activity-test.toml"],
importpath = "go-common/app/interface/main/activity/cmd",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/activity/conf:go_default_library",
"//app/interface/main/activity/http:go_default_library",
"//app/interface/main/activity/rpc/server:go_default_library",
"//app/interface/main/activity/service/like:go_default_library",
"//library/ecode/tip:go_default_library",
"//library/log:go_default_library",
"//library/net/trace:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,196 @@
[rule]
guessCount = 5
maxGuessCoin = 1
suitPids = [1]
suitExpire = 100
tickQq = "1m"
qqTryCount = 5
dTimeout = "3s"
qqStartTime = "20180101"
qqEndTime = "20181231"
qqYear = "2017"
playerYear = "2017"
bwsMids = [111,222,333,908085]
bwsAwardMids = [444]
bwsLotteryMids = [555]
bwsLotteryAids = [3,4,5,6]
needInitAchieve = true
dialectTags = [1,2,3]
dialectRegions = [1,2,3]
dialectSid = 111
spylike = 40
lotteryActID = 313
[rpcServer]
proto = "tcp"
addr = ":6889"
[httpClient]
key = "33ac033ce123e590"
secret = "0b2847315d32989a248294e350ac3ede"
dial = "500ms"
timeout = "2s"
keepAlive = "60s"
[httpClientSports]
key = "33ac033ce123e590"
secret = "0b2847315d32989a248294e350ac3ede"
dial = "1s"
timeout = "3s"
keepAlive = "60s"
[httpClientBnj]
key = "33ac033ce123e590"
secret = "0b2847315d32989a248294e350ac3ede"
dial = "500ms"
timeout = "300ms"
keepAlive = "60s"
[httpClientKfc]
key = "33ac033ce123e590"
secret = "0b2847315d32989a248294e350ac3ede"
dial = "500ms"
timeout = "300ms"
keepAlive = "60s"
[databus]
[databus.bnj]
key = "9765cdac5894f2ba"
secret = "f4237d712c3ed1e7fab0137b81418b14"
group = "ActBnjPreview-MainWebSvr-P"
topic = "ActBnjPreview-T"
action = "pub"
idle = 100
active = 100
dialTimeout = "1s"
readTimeout = "60s"
writeTimeout = "1s"
idleTimeout = "10s"
[memcache]
accessExpire = "10s"
likeExpire = "3s"
likeIPExpire = "30s"
perpetualExpire = "0s"
itemExpire = "60s"
qqExpire = "600s"
bwsExpire = "600m"
kfcExpire = "10m"
kfcCodeExpire = "1h"
sourceItemExpire = "5m"
protocolExpire = "1h"
[memcache.like]
name = "go-common/app/interface/main/activity/test"
proto = "tcp"
addr = "172.18.33.61:11220"
idle = 5
active = 10
dialTimeout = "1s"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "80s"
[redis]
name = "activity-service"
proto = "tcp"
addr = "127.0.0.1:32770"
idle = 100
active = 100
dialTimeout = "1s"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "10s"
expire = "10s"
matchExpire = "24h"
followExpire = "2400h"
userAchExpire = "1h"
userPointExpire = "1h"
achCntExpire = "1h"
hotDotExpire = "720h"
randomExpire = "300s"
resetExpire = "5s"
rewardExpire = "720h"
[rpcClient2]
[rpcClient2.account]
timeout = "1s"
[rpcClient2.archive]
timeout = "1s"
[rpcClient2.coin]
timeout = "1s"
[rpcClient2.suit]
timeout = "1s"
[mysql]
[mysql.like]
addr = "172.16.33.205:3308"
dsn = "test:test@tcp(172.16.33.205:3308)/bilibili_lottery?timeout=5s&readTimeout=5s&writeTimeout=5s&parseTime=true&loc=Local&charset=utf8,utf8mb4"
active = 5
idle = 2
idleTimeout ="4h"
queryTimeout = "1s"
execTimeout = "1s"
tranTimeout = "2s"
[mysql.like.breaker]
window ="3s"
sleep ="100ms"
bucket = 10
ratio = 0.5
[host]
sports = "http://open.sports.qq.com"
qqNews = "http://openapi.inews.qq.com"
activity = "http://www.bilibili.com"
apiCo = "http://api.bilibili.co"
liveCo ="http://api.live.bilibili.co"
[interval]
newestSubTsInterval = "10m"
pullArcTypeInterval = "10m"
actSourceInterval = "10m"
[bnj2019]
timelinePic = "//activity.hdslb.com/blackboard/static/20180122/3f23658826b7a0a46f812d368533dc9f/images/j60y4n9j83.png"
gameCancel = 0
[[bnj2019.timeline]]
name = "1111"
start = "2018-06-04T00:00:00+08:00"
end = "2018-06-05T10:00:00+08:00"
cover = "//activity.hdslb.com/blackboard/static/20180122/3f23658826b7a0a46f812d368533dc9f/images/j60y4n9j83.png"
[[bnj2019.timeline]]
name = "2222"
start = "2018-06-04T00:00:00+08:00"
end = "2018-06-05T10:00:00+08:00"
cover = "//i0.hdslb.com/bfs/activity-plat/cover/20180209/m6pvmmnpxx.jpg"
[[bnj2019.reward]]
step = 1
condition = 1000000
rewardID = "111"
expire = 365
rewardType = "pendant"
[[bnj2019.reward]]
step = 2
condition = 2000000
rewardID = "111"
rewardType = "medal"
[[bnj2019.reward]]
step = 3
condition = 3000000
rewardID = "111"
rewardType = "coupon"
[[bnj2019.reward]]
step = 4
condition = 4000000
rewardID = "111"
rewardType = "live"
[[bnj2019.info]]
nav = "nav1"
pic = "//activity.hdslb.com/blackboard/static/20180122/3f23658826b7a0a46f812d368533dc9f/images/j60y4n9j83.png"
aid = 10111175
detail = "detail1"
publish = "2018-11-29T00:00:00+08:00"
[[bnj2019.info]]
nav = "nav2"
pic = "//activity.hdslb.com/blackboard/static/20180122/3f23658826b7a0a46f812d368533dc9f/images/j60y4n9j83.png"
aid = 10111172
detail = "detail2"
publish = "2018-11-29T00:00:00+08:00"

View File

@@ -0,0 +1,54 @@
package main
import (
"flag"
"os"
"os/signal"
"syscall"
"go-common/app/interface/main/activity/conf"
"go-common/app/interface/main/activity/http"
rpc "go-common/app/interface/main/activity/rpc/server"
"go-common/app/interface/main/activity/service/like"
ecode "go-common/library/ecode/tip"
"go-common/library/log"
"go-common/library/net/trace"
)
func main() {
flag.Parse()
if err := conf.Init(); err != nil {
log.Error("conf.Init() error(%v)", err)
panic(err)
}
// init log
log.Init(conf.Conf.Log)
trace.Init(conf.Conf.Tracer)
defer trace.Close()
defer log.Close()
log.Info("activity start")
// ecode
ecode.Init(conf.Conf.Ecode)
// service init
svr := like.New(conf.Conf)
rpcSvr := rpc.New(conf.Conf, svr)
http.Init(conf.Conf)
// init signal
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
for {
s := <-c
log.Info("activity get a signal %s", s.String())
switch s {
case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGSTOP, syscall.SIGINT:
rpcSvr.Close()
http.CloseService()
log.Info("activity exit")
return
case syscall.SIGHUP:
// TODO reload
default:
return
}
}
}

View File

@@ -0,0 +1,49 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["conf.go"],
importpath = "go-common/app/interface/main/activity/conf",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/activity/model/bnj:go_default_library",
"//library/cache/memcache:go_default_library",
"//library/cache/redis:go_default_library",
"//library/conf:go_default_library",
"//library/database/elastic:go_default_library",
"//library/database/hbase.v2:go_default_library",
"//library/database/sql:go_default_library",
"//library/ecode/tip:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/net/http/blademaster/middleware/auth:go_default_library",
"//library/net/http/blademaster/middleware/verify:go_default_library",
"//library/net/rpc:go_default_library",
"//library/net/rpc/warden:go_default_library",
"//library/net/trace:go_default_library",
"//library/queue/databus:go_default_library",
"//library/stat/prom:go_default_library",
"//library/time:go_default_library",
"//vendor/github.com/BurntSushi/toml:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,301 @@
package conf
import (
"errors"
"flag"
xtime "time"
"go-common/app/interface/main/activity/model/bnj"
"go-common/library/cache/memcache"
"go-common/library/cache/redis"
"go-common/library/conf"
"go-common/library/database/elastic"
"go-common/library/database/sql"
ecode "go-common/library/ecode/tip"
"go-common/library/log"
"go-common/library/net/http/blademaster"
"go-common/library/net/http/blademaster/middleware/auth"
"go-common/library/net/http/blademaster/middleware/verify"
"go-common/library/net/rpc"
"go-common/library/net/rpc/warden"
"go-common/library/net/trace"
"go-common/library/queue/databus"
"go-common/library/stat/prom"
"go-common/library/time"
"go-common/library/database/hbase.v2"
"github.com/BurntSushi/toml"
)
var (
confPath string
client *conf.Client
// Conf is global config
Conf = &Config{}
)
// Config service config
type Config struct {
Static string
// reload
Reload ReloadInterval
// auth
Auth *auth.Config
// verify
Verify *verify.Config
// HTTPServer
HTTPServer *blademaster.ServerConfig
// tracer
Tracer *trace.Config
// db
MySQL *MySQL
// rpc
RPCClient2 *RPCClient2
// grpc
TagClient *warden.ClientConfig
// acc client
AccClient *warden.ClientConfig
// httpClient
HTTPClient *blademaster.ClientConfig
// HTTPClientSports
HTTPClientSports *blademaster.ClientConfig
// HTTPClientBnj
HTTPClientBnj *blademaster.ClientConfig
// HTTPClientKfc
HTTPClientKfc *blademaster.ClientConfig
// Rule
Rule *Rule
// Host
Host Host
// Log
Log *log.Config
// ecode
Ecode *ecode.Config
// ip
IPFile string
// mc
Memcache *Memcache
TimeMc *tmMC
// redis
Redis *Redis
// hbase
Hbase *hbase.Config
RPCServer *rpc.ServerConfig
// interval
Interval *Interval
// Elastic
Elastic *elastic.Config
// ArcClient
ArcClient *warden.ClientConfig
// Time machine conf
Timemachine *timemachine
// Bnj
Bnj2019 *bnj2019
// databus
Databus *Databus
}
// Host remote host.
type Host struct {
Sports string
QqNews string
Activity string
APICo string
Mall string
LiveCo string
}
// Rule rule config.
type Rule struct {
GuessCount int
MaxGuessCoin int64
SuitPids []int64
SuitExpire int64
TickQq time.Duration
QqTryCount int
DTimeout time.Duration
QqStartTime string
QqEndTime string
QqYear string
PlayerYear string
BwsMids []int64
BwsAwardMids []int64
BwsLotteryMids []int64
BwsLotteryAids []int64
BwsSuitExpire int64
NeedInitAchieve bool
DialectTags []int64
DialectRegions []int16
DialectSid int64
SpecialSids []int64
Spylike int64
LotteryActID int64
MatchLotteryID int64
S8Sid int64
S8ArcSid int64
S8ArtSid int64
KingStorySid int64
TmMids []int64
}
// Interval .
type Interval struct {
NewestSubTsInterval time.Duration
PullArcTypeInterval time.Duration
ActSourceInterval time.Duration
TmInternal time.Duration
}
// Prom prom .
type Prom struct {
LIBClient *prom.Prom
LIBClientState *prom.Prom
APIClient *prom.Prom
HTTPServer *prom.Prom
}
// MySQL define MySQL config
type MySQL struct {
Like *sql.Config
}
// ReloadInterval define reolad config
type ReloadInterval struct {
Jobs time.Duration
Notice time.Duration
Ad time.Duration
}
// RPCClient2 define RPC client config
type RPCClient2 struct {
Archive *rpc.ClientConfig
Coin *rpc.ClientConfig
Suit *rpc.ClientConfig
Spy *rpc.ClientConfig
Tag *rpc.ClientConfig
Thumbup *rpc.ClientConfig
Article *rpc.ClientConfig
}
// Redis struct
type Redis struct {
*redis.Config
Expire time.Duration
MatchExpire time.Duration
FollowExpire time.Duration
UserAchExpire time.Duration
UserPointExpire time.Duration
AchCntExpire time.Duration
HotDotExpire time.Duration
RandomExpire time.Duration
ResetExpire time.Duration
RewardExpire time.Duration
}
// Memcache struct
type Memcache struct {
Like *memcache.Config
LikeExpire time.Duration
LikeIPExpire time.Duration
PerpetualExpire time.Duration
ItemExpire time.Duration
SubStatExpire time.Duration
ViewRankExpire time.Duration
SourceItemExpire time.Duration
QqExpire time.Duration
BwsExpire time.Duration
ProtocolExpire time.Duration
KfcExpire time.Duration
KfcCodeExpire time.Duration
}
type tmMC struct {
Timemachine *memcache.Config
TmExpire time.Duration
}
type timemachine struct {
TagDescID int64
TagRegionDescID int64
RegionDescID int64
}
type bnj2019 struct {
ActID int64
SubID int64
GameCancel int64
AdminCheck int64
Admins []int64
TimelinePic string
H5TimelinePic string
Start xtime.Time
Reward []*bnj.Reward
Info []*struct {
Nav string
Pic string
H5Pic string
Aid int64
Detail string
H5Detail string
Nickname string
Publish xtime.Time
}
}
// Databus .
type Databus struct {
Bnj *databus.Config
}
func init() {
flag.StringVar(&confPath, "conf", "", "config path")
}
func local() (err error) {
_, err = toml.DecodeFile(confPath, &Conf)
return
}
// Init conf.
func Init() error {
if confPath != "" {
return local()
}
return remote()
}
func remote() (err error) {
if client, err = conf.New(); err != nil {
return
}
if err = load(); err != nil {
return
}
client.Watch("activity.toml")
go func() {
for range client.Event() {
log.Info("config reload")
if load() != nil {
log.Error("config reload error (%v)", err)
}
}
}()
return
}
func load() (err error) {
var (
s string
ok bool
tmpConf *Config
)
if s, ok = client.Toml2(); !ok {
return errors.New("load config center error")
}
if _, err = toml.Decode(s, &tmpConf); err != nil {
return errors.New("could not decode config")
}
*Conf = *tmpConf
return
}

View File

@@ -0,0 +1,63 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = [
"cache.go",
"coupon.go",
"dao.go",
"mc.cache.go",
"redis.go",
],
importpath = "go-common/app/interface/main/activity/dao/bnj",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/activity/conf:go_default_library",
"//library/cache/memcache:go_default_library",
"//library/cache/redis:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/stat/prom:go_default_library",
"//vendor/github.com/pkg/errors:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)
go_test(
name = "go_default_test",
srcs = [
"cache_test.go",
"coupon_test.go",
"dao_test.go",
"mc.cache_test.go",
"redis_test.go",
],
embed = [":go_default_library"],
tags = ["automanaged"],
deps = [
"//app/interface/main/activity/conf:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
"//vendor/gopkg.in/h2non/gock.v1:go_default_library",
],
)

View File

@@ -0,0 +1,21 @@
package bnj
import "context"
func timeFinishKey() string {
return "time_finish"
}
func timeLessKey() string {
return "time_less"
}
//go:generate $GOPATH/src/go-common/app/tool/cache/mc
type _mc interface {
// mc: -key=timeFinishKey
CacheTimeFinish(c context.Context) (int64, error)
// mc: -key=timeFinishKey
DelCacheTimeFinish(c context.Context) (int64, error)
// mc: -key=timeLessKey
DelCacheTimeLess(c context.Context) (int64, error)
}

View File

@@ -0,0 +1,18 @@
package bnj
import (
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestBnjtimeFinishKey(t *testing.T) {
convey.Convey("timeFinishKey", t, func(ctx convey.C) {
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1 := timeFinishKey()
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,47 @@
package bnj
import (
"context"
"encoding/json"
"net/http"
"strings"
"go-common/library/ecode"
"github.com/pkg/errors"
)
const _grantCouponURL = "/mall-marketing/coupon_code/create"
// GrantCoupon grant coupon to mid.
func (d *Dao) GrantCoupon(c context.Context, mid int64, couponID string) (err error) {
var (
bs []byte
req *http.Request
)
param := &struct {
Mid int64 `json:"mid"`
CouponID string `json:"couponId"`
}{
Mid: mid,
CouponID: couponID,
}
if bs, err = json.Marshal(param); err != nil {
return
}
if req, err = http.NewRequest(http.MethodPost, d.grantCouponURL, strings.NewReader(string(bs))); err != nil {
return
}
req.Header.Set("Content-Type", "application/json")
var res struct {
Code int `json:"code"`
Msg string `json:"message"`
}
if err = d.client.Do(c, req, &res); err != nil {
return
}
if res.Code != ecode.OK.Code() {
err = errors.Wrap(ecode.Int(res.Code), d.grantCouponURL+"msg:"+res.Msg)
}
return
}

View File

@@ -0,0 +1,28 @@
package bnj
import (
"context"
"testing"
"gopkg.in/h2non/gock.v1"
"github.com/smartystreets/goconvey/convey"
)
func TestBnjGrantCoupon(t *testing.T) {
convey.Convey("GrantCoupon", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2080809)
couponID = "3d005e8ba01c5cb0"
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("POST", d.grantCouponURL).Reply(200).JSON(`{"code":0}`)
err := d.GrantCoupon(c, mid, couponID)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,45 @@
package bnj
import (
"time"
"go-common/app/interface/main/activity/conf"
"go-common/library/cache/memcache"
"go-common/library/cache/redis"
xhttp "go-common/library/net/http/blademaster"
)
// Dao bnj dao.
type Dao struct {
c *conf.Config
mc *memcache.Pool
redis *redis.Pool
client *xhttp.Client
resetExpire int32
rewardExpire int32
grantCouponURL string
}
// New init bnj dao.
func New(c *conf.Config) *Dao {
d := &Dao{
c: c,
mc: memcache.NewPool(c.Memcache.Like),
redis: redis.NewPool(c.Redis.Config),
client: xhttp.NewClient(c.HTTPClientBnj),
resetExpire: int32(time.Duration(c.Redis.ResetExpire) / time.Second),
rewardExpire: int32(time.Duration(c.Redis.RewardExpire) / time.Second),
}
d.grantCouponURL = d.c.Host.Mall + _grantCouponURL
return d
}
// Close .
func (d *Dao) Close() {
if d.mc != nil {
d.mc.Close()
}
if d.redis != nil {
d.redis.Close()
}
}

View File

@@ -0,0 +1,45 @@
package bnj
import (
"flag"
"os"
"strings"
"testing"
"go-common/app/interface/main/activity/conf"
"gopkg.in/h2non/gock.v1"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "dev" {
flag.Set("app_id", "main.web-svr.activity")
flag.Set("conf_token", "22edc93e2998bf0cb0bbee661b03d41f")
flag.Set("tree_id", "2873")
flag.Set("conf_version", "docker-1")
flag.Set("deploy_env", "uat")
flag.Set("conf_host", "config.bilibili.co")
flag.Set("conf_path", "/tmp")
flag.Set("region", "sh")
flag.Set("zone", "sh001")
} else {
flag.Set("conf", "../../cmd/activity-test.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
d.client.SetTransport(gock.DefaultTransport)
os.Exit(m.Run())
}
func httpMock(method, url string) *gock.Request {
r := gock.New(url)
r.Method = strings.ToUpper(method)
return r
}

View File

@@ -0,0 +1,94 @@
// Code generated by $GOPATH/src/go-common/app/tool/cache/mc. DO NOT EDIT.
/*
Package bnj is a generated mc cache package.
It is generated from:
type _mc interface {
// mc: -key=timeFinishKey
CacheTimeFinish(c context.Context) (int64, error)
// mc: -key=timeFinishKey
DelCacheTimeFinish(c context.Context) (int64, error)
// mc: -key=timeLessKey
DelCacheTimeLess(c context.Context) (int64, error)
}
*/
package bnj
import (
"context"
"fmt"
"strconv"
"go-common/library/cache/memcache"
"go-common/library/log"
"go-common/library/stat/prom"
)
var _ _mc
// CacheTimeFinish get data from mc
func (d *Dao) CacheTimeFinish(c context.Context) (res int64, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := timeFinishKey()
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheTimeFinish")
log.Errorv(c, log.KV("CacheTimeFinish", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
var v string
err = conn.Scan(reply, &v)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheTimeFinish")
log.Errorv(c, log.KV("CacheTimeFinish", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
r, err := strconv.ParseInt(v, 10, 64)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheTimeFinish")
log.Errorv(c, log.KV("CacheTimeFinish", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = int64(r)
return
}
// DelCacheTimeFinish delete data from mc
func (d *Dao) DelCacheTimeFinish(c context.Context) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := timeFinishKey()
if err = conn.Delete(key); err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:DelCacheTimeFinish")
log.Errorv(c, log.KV("DelCacheTimeFinish", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// DelCacheTimeLess delete data from mc
func (d *Dao) DelCacheTimeLess(c context.Context) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := timeLessKey()
if err = conn.Delete(key); err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:DelCacheTimeLess")
log.Errorv(c, log.KV("DelCacheTimeLess", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}

View File

@@ -0,0 +1,51 @@
package bnj
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestBnjCacheTimeFinish(t *testing.T) {
convey.Convey("CacheTimeFinish", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.CacheTimeFinish(c)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestBnjDelCacheTimeFinish(t *testing.T) {
convey.Convey("DelCacheTimeFinish", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.DelCacheTimeFinish(c)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestBnjDelCacheTimeLess(t *testing.T) {
convey.Convey("DelCacheTimeLess", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.DelCacheTimeLess(c)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,89 @@
package bnj
import (
"context"
"fmt"
"go-common/library/cache/redis"
"go-common/library/log"
)
func resetKey(mid int64) string {
return fmt.Sprintf("bnj_%d", mid)
}
func rewardKey(mid, subID int64, step int) string {
return fmt.Sprintf("bnj_rwd_%d_%d_%d", mid, subID, step)
}
// CacheResetCD .
func (d *Dao) CacheResetCD(c context.Context, mid int64, cd int32) (bool, error) {
resetCD := d.resetExpire
if cd > 0 {
resetCD = cd
}
return d.setNXLockCache(c, resetKey(mid), resetCD)
}
// TTLResetCD get reset cd ttl
func (d *Dao) TTLResetCD(c context.Context, mid int64) (ttl int64, err error) {
key := resetKey(mid)
conn := d.redis.Get(c)
defer conn.Close()
if ttl, err = redis.Int64(conn.Do("TTL", key)); err != nil {
log.Error("TTLResetCD conn.Do(TTL, %s), error(%v)", key, err)
}
return
}
// CacheHasReward .
func (d *Dao) CacheHasReward(c context.Context, mid, subID int64, step int) (bool, error) {
return d.setNXLockCache(c, rewardKey(mid, subID, step), d.rewardExpire)
}
// DelCacheHasReward .
func (d *Dao) DelCacheHasReward(c context.Context, mid, subID int64, step int) error {
return d.delNXLockCache(c, rewardKey(mid, subID, step))
}
// HasReward .
func (d *Dao) HasReward(c context.Context, mid, subID int64, step int) (res bool, err error) {
conn := d.redis.Get(c)
defer conn.Close()
key := rewardKey(mid, subID, step)
if res, err = redis.Bool(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
return
}
log.Error("HasReward conn.Do(GET(%s)) error(%v)", key, err)
}
return
}
func (d *Dao) setNXLockCache(c context.Context, key string, times int32) (res bool, err error) {
conn := d.redis.Get(c)
defer conn.Close()
if res, err = redis.Bool(conn.Do("SETNX", key, "1")); err != nil {
if err == redis.ErrNil {
err = nil
} else {
log.Error("conn.Do(SETNX(%s)) error(%v)", key, err)
return
}
}
if res {
if _, err = redis.Bool(conn.Do("EXPIRE", key, times)); err != nil {
log.Error("conn.Do(EXPIRE, %s, %d) error(%v)", key, times, err)
return
}
}
return
}
func (d *Dao) delNXLockCache(c context.Context, key string) (err error) {
conn := d.redis.Get(c)
defer conn.Close()
_, err = conn.Do("DEL", key)
return
}

View File

@@ -0,0 +1,157 @@
package bnj
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestBnjresetKey(t *testing.T) {
convey.Convey("resetKey", t, func(ctx convey.C) {
var (
mid = int64(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1 := resetKey(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestBnjrewardKey(t *testing.T) {
convey.Convey("rewardKey", t, func(ctx convey.C) {
var (
mid = int64(0)
subID = int64(0)
step = int(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1 := rewardKey(mid, subID, step)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestBnjCacheResetCD(t *testing.T) {
convey.Convey("CacheResetCD", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
expire = int32(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1, err := d.CacheResetCD(c, mid, expire)
ctx.Convey("Then err should be nil.p1 should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestBnjTTLResetCD(t *testing.T) {
convey.Convey("CacheTTLResetCD", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1, err := d.TTLResetCD(c, mid)
ctx.Convey("Then err should be nil.p1 should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestBnjCacheHasReward(t *testing.T) {
convey.Convey("CacheHasReward", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
subID = int64(0)
step = int(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1, err := d.CacheHasReward(c, mid, subID, step)
ctx.Convey("Then err should be nil.p1 should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestBnjDelCacheHasReward(t *testing.T) {
convey.Convey("DelCacheHasReward", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
subID = int64(0)
step = int(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.DelCacheHasReward(c, mid, subID, step)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestBnjHasReward(t *testing.T) {
convey.Convey("HasReward", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(27515251)
subID = int64(0)
step = int(1)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.HasReward(c, mid, subID, step)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
ctx.Printf("%+v", res)
})
})
})
}
func TestBnjsetNXLockCache(t *testing.T) {
convey.Convey("setNXLockCache", t, func(ctx convey.C) {
var (
c = context.Background()
key = ""
times = int32(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.setNXLockCache(c, key, times)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestBnjdelNXLockCache(t *testing.T) {
convey.Convey("delNXLockCache", t, func(ctx convey.C) {
var (
c = context.Background()
key = ""
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.delNXLockCache(c, key)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,63 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = [
"achievement.go",
"bws.go",
"cache.go",
"dao.cache.go",
"mc.cache.go",
"point.go",
],
importpath = "go-common/app/interface/main/activity/dao/bws",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/activity/conf:go_default_library",
"//app/interface/main/activity/model/bws:go_default_library",
"//library/cache/memcache:go_default_library",
"//library/cache/redis:go_default_library",
"//library/database/sql:go_default_library",
"//library/log:go_default_library",
"//library/stat/prom:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)
go_test(
name = "go_default_test",
srcs = [
"achievement_test.go",
"bws_test.go",
"point_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/activity/conf:go_default_library",
"//app/interface/main/activity/model/bws:go_default_library",
"//library/time:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)

View File

@@ -0,0 +1,390 @@
package bws
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"strconv"
"time"
bwsmdl "go-common/app/interface/main/activity/model/bws"
"go-common/library/cache/redis"
xsql "go-common/library/database/sql"
"go-common/library/log"
)
const (
_userAchieveKeyFmt = "bws_u_a_%d_%s"
_userAchieveCntFmt = "bws_a_c_%d_%s"
_bwsLotteryKeyFmt = "bws_l_%s_%d"
_awardSQL = "UPDATE act_bws_user_achievements SET award = 2 where `key`= ? AND aid = ?"
_achievementsSQL = "SELECT id,`name`,icon,dic,link_type,`unlock`,bid,icon_big,icon_active,icon_active_big,award,ctime,mtime,image,suit_id FROM act_bws_achievements WHERE del = 0 AND bid = ? ORDER BY ID"
_userAchieveSQL = "SELECT id,aid,award FROM act_bws_user_achievements WHERE bid = ? AND `key` = ? AND del = 0"
_userAchieveAddSQL = "INSERT INTO act_bws_user_achievements(bid,aid,award,`key`) VALUES(?,?,?,?)"
_countAchievesSQL = "SELECT aid,COUNT(1) AS c FROM act_bws_user_achievements WHERE del = 0 AND bid = ? AND ctime BETWEEN ? AND ? GROUP BY aid HAVING c > 0"
_nextDayHour = 16
)
func keyUserAchieve(bid int64, key string) string {
return fmt.Sprintf(_userAchieveKeyFmt, bid, key)
}
func keyAchieveCnt(bid int64, day string) string {
return fmt.Sprintf(_userAchieveCntFmt, bid, day)
}
func keyLottery(aid int64, day string) string {
if day == "" {
day = time.Now().Format("20060102")
}
return fmt.Sprintf(_bwsLotteryKeyFmt, day, aid)
}
// Award achievement award
func (d *Dao) Award(c context.Context, key string, aid int64) (err error) {
if _, err = d.db.Exec(c, _awardSQL, key, aid); err != nil {
log.Error("Award: db.Exec(%d,%s) error(%v)", aid, key, err)
}
return
}
// RawAchievements achievements list
func (d *Dao) RawAchievements(c context.Context, bid int64) (res *bwsmdl.Achievements, err error) {
var (
rows *xsql.Rows
rs []*bwsmdl.Achievement
)
if rows, err = d.db.Query(c, _achievementsSQL, bid); err != nil {
log.Error("RawAchievements: db.Exec(%d) error(%v)", bid, err)
return
}
defer rows.Close()
for rows.Next() {
r := new(bwsmdl.Achievement)
if err = rows.Scan(&r.ID, &r.Name, &r.Icon, &r.Dic, &r.LockType, &r.Unlock, &r.Bid, &r.IconBig, &r.IconActive, &r.IconActiveBig, &r.Award, &r.Ctime, &r.Mtime, &r.Image, &r.SuitID); err != nil {
log.Error("RawAchievements:row.Scan() error(%v)", err)
return
}
rs = append(rs, r)
}
if len(rs) > 0 {
res = new(bwsmdl.Achievements)
res.Achievements = rs
}
return
}
// RawUserAchieves get user achievements from db.
func (d *Dao) RawUserAchieves(c context.Context, bid int64, key string) (rs []*bwsmdl.UserAchieve, err error) {
var (
rows *xsql.Rows
)
if rows, err = d.db.Query(c, _userAchieveSQL, bid, key); err != nil {
log.Error("RawUserAchieves: db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
r := new(bwsmdl.UserAchieve)
if err = rows.Scan(&r.ID, &r.Aid, &r.Award); err != nil {
log.Error("RawUserAchieves:row.Scan() error(%v)", err)
return
}
rs = append(rs, r)
}
return
}
// RawAchieveCounts achievements user count
func (d *Dao) RawAchieveCounts(c context.Context, bid int64, day string) (res []*bwsmdl.CountAchieves, err error) {
var (
rows *xsql.Rows
)
start, _ := time.Parse("20060102-15:04:05", day+"-00:00:00")
end, _ := time.Parse("20060102-15:04:05", day+"-23:59:59")
if rows, err = d.db.Query(c, _countAchievesSQL, bid, start, end); err != nil {
log.Error("RawCountAchieves: db.Exec(%d) error(%v)", bid, err)
return
}
defer rows.Close()
for rows.Next() {
r := new(bwsmdl.CountAchieves)
if err = rows.Scan(&r.Aid, &r.Count); err != nil {
log.Error("RawCountAchieves:row.Scan() error(%v)", err)
return
}
res = append(res, r)
}
return
}
// AddUserAchieve .
func (d *Dao) AddUserAchieve(c context.Context, bid, aid, award int64, key string) (lastID int64, err error) {
var res sql.Result
if res, err = d.db.Exec(c, _userAchieveAddSQL, bid, aid, award, key); err != nil {
log.Error("AddUserAchieve error d.db.Exec(%d,%d,%s) error(%v)", bid, aid, key, err)
return
}
return res.LastInsertId()
}
// CacheUserAchieves .
func (d *Dao) CacheUserAchieves(c context.Context, bid int64, key string) (res []*bwsmdl.UserAchieve, err error) {
var (
values []interface{}
cacheKey = keyUserAchieve(bid, key)
conn = d.redis.Get(c)
)
defer conn.Close()
if values, err = redis.Values(conn.Do("ZRANGE", cacheKey, 0, -1)); err != nil {
log.Error("CacheUserAchieves conn.Do(ZRANGE, %s) error(%v)", cacheKey, err)
return
} else if len(values) == 0 {
return
}
for len(values) > 0 {
var bs []byte
if values, err = redis.Scan(values, &bs); err != nil {
log.Error("CacheUserAchieves redis.Scan(%v) error(%v)", values, err)
return
}
item := new(bwsmdl.UserAchieve)
if err = json.Unmarshal(bs, &item); err != nil {
log.Error("CacheUserAchieves conn.Do(ZRANGE, %s) error(%v)", cacheKey, err)
continue
}
res = append(res, item)
}
return
}
// AddCacheUserAchieves .
func (d *Dao) AddCacheUserAchieves(c context.Context, bid int64, data []*bwsmdl.UserAchieve, key string) (err error) {
var bs []byte
if len(data) == 0 {
return
}
cacheKey := keyUserAchieve(bid, key)
conn := d.redis.Get(c)
defer conn.Close()
args := redis.Args{}.Add(cacheKey)
for _, v := range data {
if bs, err = json.Marshal(v); err != nil {
log.Error("AddCacheUserAchieves json.Marshal() error(%v)", err)
return
}
args = args.Add(v.ID).Add(bs)
}
if err = conn.Send("ZADD", args...); err != nil {
log.Error("AddCacheUserAchieves conn.Send(ZADD, %s, %v) error(%v)", cacheKey, args, err)
return
}
if err = conn.Send("EXPIRE", cacheKey, d.userAchExpire); err != nil {
log.Error("AddCacheUserAchieves conn.Send(Expire, %s) error(%v)", cacheKey, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("AddCacheUserAchieves conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("AddCacheUserAchieves conn.Receive() error(%v)", err)
return
}
}
return
}
// DelCacheUserAchieves .
func (d *Dao) DelCacheUserAchieves(c context.Context, bid int64, key string) (err error) {
cacheKey := keyUserAchieve(bid, key)
conn := d.redis.Get(c)
defer conn.Close()
if _, err = conn.Do("DEL", cacheKey); err != nil {
log.Error("DelCacheUserAchieves conn.Do(DEL) key(%s) error(%v)", cacheKey, err)
}
return
}
// AppendUserAchievesCache .
func (d *Dao) AppendUserAchievesCache(c context.Context, bid int64, key string, achieve *bwsmdl.UserAchieve) (err error) {
var (
bs []byte
ok bool
cacheKey = keyUserAchieve(bid, key)
conn = d.redis.Get(c)
)
defer conn.Close()
if ok, err = redis.Bool(conn.Do("EXPIRE", cacheKey, d.userAchExpire)); err != nil || !ok {
log.Error("AppendUserAchievesCache conn.Do(EXPIRE %s) error(%v)", key, err)
return
}
args := redis.Args{}.Add(cacheKey)
if bs, err = json.Marshal(achieve); err != nil {
log.Error("AppendUserAchievesCache json.Marshal() error(%v)", err)
return
}
args = args.Add(achieve.ID).Add(bs)
if err = conn.Send("ZADD", args...); err != nil {
log.Error("AddCacheUserAchieves conn.Send(ZADD, %s, %v) error(%v)", cacheKey, args, err)
return
}
if err = conn.Send("EXPIRE", cacheKey, d.userAchExpire); err != nil {
log.Error("AddCacheUserAchieves conn.Send(Expire, %s) error(%v)", cacheKey, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("AddCacheUserAchieves conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("AddCacheUserAchieves conn.Receive() error(%v)", err)
return
}
}
return
}
// CacheAchieveCounts get achieve counts from cache
func (d *Dao) CacheAchieveCounts(c context.Context, bid int64, day string) (res []*bwsmdl.CountAchieves, err error) {
var (
bss []int64
key = keyAchieveCnt(bid, day)
conn = d.redis.Get(c)
)
defer conn.Close()
if bss, err = redis.Int64s(conn.Do("HGETALL", key)); err != nil {
log.Error("CacheAchieveCounts conn.Do(HGETALL,%s) error(%v)", key, err)
return
}
for i := 1; i < len(bss); i += 2 {
item := &bwsmdl.CountAchieves{Aid: bss[i-1], Count: bss[i]}
res = append(res, item)
}
return
}
// AddCacheAchieveCounts set achieve counts to cache
func (d *Dao) AddCacheAchieveCounts(c context.Context, bid int64, res []*bwsmdl.CountAchieves, day string) (err error) {
if len(res) == 0 {
return
}
key := keyAchieveCnt(bid, day)
conn := d.redis.Get(c)
defer conn.Close()
if err = conn.Send("DEL", key); err != nil {
log.Error("AddCacheAchieveCounts conn.Send(DEL, %s) error(%v)", key, err)
return
}
args := redis.Args{}.Add(key)
for _, v := range res {
args = args.Add(v.Aid).Add(v.Count)
}
if err = conn.Send("HMSET", args...); err != nil {
log.Error("AddCacheAchieveCounts conn.Send(HMSET, %s) error(%v)", key, err)
return
}
if err = conn.Send("EXPIRE", key, d.achCntExpire); err != nil {
log.Error("AddCacheAchieveCounts conn.Send(Expire, %s, %d) error(%v)", key, d.achCntExpire, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("AddCacheAchieveCounts conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}
// IncrCacheAchieveCounts incr achieve counts to cache
func (d *Dao) IncrCacheAchieveCounts(c context.Context, bid, aid int64, day string) (err error) {
var (
key = keyAchieveCnt(bid, day)
conn = d.redis.Get(c)
)
defer conn.Close()
if err = conn.Send("EXPIRE", key, d.achCntExpire); err != nil {
log.Error("IncrCacheAchieveCounts conn.Send(Expire, %s, %d) error(%v)", key, d.achCntExpire, err)
return
}
if err = conn.Send("HINCRBY", key, aid, 1); err != nil {
log.Error("IncrCacheAchieveCounts conn.Send(HMSET, %s, %d) error(%v)", key, aid, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("IncrCacheAchieveCounts conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}
// DelCacheAchieveCounts delete achieve cnt cache.
func (d *Dao) DelCacheAchieveCounts(c context.Context, bid int64, day string) (err error) {
cacheKey := keyAchieveCnt(bid, day)
conn := d.redis.Get(c)
defer conn.Close()
if _, err = conn.Do("DEL", cacheKey); err != nil {
log.Error("DelCacheAchieveCounts conn.Do(DEL) key(%s) error(%v)", cacheKey, err)
}
return
}
// AddLotteryMidCache add lottery mid cache.
func (d *Dao) AddLotteryMidCache(c context.Context, aid, mid int64) (err error) {
now := time.Now()
hour := now.Hour()
dayInt, _ := strconv.ParseInt(now.Format("20060102"), 10, 64)
if hour >= _nextDayHour {
dayInt = dayInt + 1
}
cacheKey := keyLottery(aid, strconv.FormatInt(dayInt, 10))
conn := d.redis.Get(c)
defer conn.Close()
if _, err = conn.Do("SADD", cacheKey, mid); err != nil {
log.Error("AddLotteryCache conn.Do(LPUSH, %s, %d) error(%v)", cacheKey, mid, err)
}
return
}
// CacheLotteryMid .
func (d *Dao) CacheLotteryMid(c context.Context, aid int64, day string) (mid int64, err error) {
var (
cacheKey = keyLottery(aid, day)
conn = d.redis.Get(c)
)
defer conn.Close()
if mid, err = redis.Int64(conn.Do("SPOP", cacheKey)); err != nil && err != redis.ErrNil {
log.Error("LotteryMidCache SPOP key(%s) error(%v)", cacheKey, err)
}
return
}
// CacheLotteryMids .
func (d *Dao) CacheLotteryMids(c context.Context, aid int64, day string) (mids []int64, err error) {
var cacheKey string
conn := d.redis.Get(c)
defer conn.Close()
cacheKey = keyLottery(aid, day)
if mids, err = redis.Int64s(conn.Do("SMEMBERS", cacheKey)); err != nil {
if err == redis.ErrNil {
err = nil
return
}
log.Error("redis.Int64s(conn.Do(SMEMEBERS,%s)) error(%v)", cacheKey, err)
}
return
}

View File

@@ -0,0 +1,100 @@
package bws
import (
"context"
"encoding/json"
"testing"
"time"
"go-common/app/interface/main/activity/model/bws"
xtime "go-common/library/time"
. "github.com/smartystreets/goconvey/convey"
)
func TestDao_CacheAchieveCounts(t *testing.T) {
Convey("test cache achieve count", t, WithDao(func(d *Dao) {
bid := int64(3)
day := "20180712"
data, err := d.CacheAchieveCounts(context.Background(), bid, day)
So(err, ShouldBeNil)
bs, _ := json.Marshal(data)
Printf("%v", string(bs))
}))
}
func TestDao_AddCacheAchieveCounts(t *testing.T) {
Convey("test add cache achieve count", t, WithDao(func(d *Dao) {
bid := int64(3)
day := "20180712"
list := []*bws.CountAchieves{
{Aid: 111, Count: 222},
{Aid: 222, Count: 333},
}
err := d.AddCacheAchieveCounts(context.Background(), bid, list, day)
So(err, ShouldBeNil)
}))
}
func TestDao_AddCacheUserAchieves(t *testing.T) {
Convey("test add cache", t, WithDao(func(d *Dao) {
bid := int64(3)
list := []*bws.UserAchieve{
{ID: 2, Aid: 3, Award: 0, Ctime: xtime.Time(time.Now().Unix())},
{ID: 3, Aid: 4, Award: 0, Ctime: xtime.Time(time.Now().Unix())},
}
key := "9abf1997abe851e6"
err := d.AddCacheUserAchieves(context.Background(), bid, list, key)
So(err, ShouldBeNil)
}))
}
func TestDao_CacheUserAchieves(t *testing.T) {
Convey("test cache user achieves", t, WithDao(func(d *Dao) {
bid := int64(3)
key := "9abf1997abe851e6"
data, err := d.CacheUserAchieves(context.Background(), bid, key)
So(err, ShouldBeNil)
bs, _ := json.Marshal(data)
Printf("%v", string(bs))
}))
}
func TestDao_AddLotteryMidCache(t *testing.T) {
Convey("test add lottery mid cache", t, WithDao(func(d *Dao) {
aid := int64(3)
mid := int64(908085)
for i := 0; i < 10; i++ {
err := d.AddLotteryMidCache(context.Background(), aid, mid+int64(i))
So(err, ShouldBeNil)
}
}))
}
func TestDao_LotteryMidCache(t *testing.T) {
Convey("test get lottery mid cache", t, WithDao(func(d *Dao) {
aid := int64(3)
mid, err := d.CacheLotteryMid(context.Background(), aid, "")
So(err, ShouldBeNil)
Println(mid)
}))
}
func TestDao_RawAchieveCounts(t *testing.T) {
Convey("test achieve count", t, WithDao(func(d *Dao) {
bid := int64(1)
day := "20180712"
data, err := d.RawAchieveCounts(context.Background(), bid, day)
So(err, ShouldBeNil)
Printf("%+v", data)
}))
}
func TestDao_RawAchievements(t *testing.T) {
Convey("test raw achievements", t, WithDao(func(d *Dao) {
bid := int64(1)
data, err := d.RawAchievements(context.Background(), bid)
So(err, ShouldBeNil)
Printf("%+v", data)
}))
}

View File

@@ -0,0 +1,111 @@
package bws
import (
"context"
"time"
"go-common/app/interface/main/activity/conf"
bwsmdl "go-common/app/interface/main/activity/model/bws"
"go-common/library/cache/memcache"
"go-common/library/cache/redis"
xsql "go-common/library/database/sql"
"go-common/library/log"
"go-common/library/stat/prom"
)
const (
_bindingSQL = "UPDATE act_bws_users SET mid = ? WHERE `key`= ?"
_usersMidSQL = "SELECT id,mid,`key`,ctime,mtime,bid FROM act_bws_users WHERE mid = ?"
_usersKeySQL = "SELECT id,mid,`key`,ctime,mtime,bid FROM act_bws_users WHERE `key` = ?"
_usersIDSQL = "SELECT id,mid,`key`,ctime,mtime,bid FROM act_bws_users WHERE id = ?"
)
// PromError stat and log.
func PromError(name string, format string, args ...interface{}) {
prom.BusinessErrCount.Incr(name)
log.Error(format, args...)
}
// Dao dao.
type Dao struct {
// config
c *conf.Config
// db
db *xsql.DB
mc *memcache.Pool
mcExpire int32
redis *redis.Pool
redisExpire int32
userAchExpire int32
userPointExpire int32
achCntExpire int32
cacheCh chan func()
}
// New dao new.
func New(c *conf.Config) (d *Dao) {
d = &Dao{
// config
c: c,
db: xsql.NewMySQL(c.MySQL.Like),
mc: memcache.NewPool(c.Memcache.Like),
mcExpire: int32(time.Duration(c.Memcache.BwsExpire) / time.Second),
redis: redis.NewPool(c.Redis.Config),
cacheCh: make(chan func(), 1024),
redisExpire: int32(time.Duration(c.Redis.Expire) / time.Second),
userAchExpire: int32(time.Duration(c.Redis.UserAchExpire) / time.Second),
userPointExpire: int32(time.Duration(c.Redis.UserPointExpire) / time.Second),
achCntExpire: int32(time.Duration(c.Redis.AchCntExpire) / time.Second),
}
return
}
// RawUsersMid get users by mid
func (d *Dao) RawUsersMid(c context.Context, mid int64) (res *bwsmdl.Users, err error) {
res = &bwsmdl.Users{}
row := d.db.QueryRow(c, _usersMidSQL, mid)
if err = row.Scan(&res.ID, &res.Mid, &res.Key, &res.Ctime, &res.Mtime, &res.Bid); err != nil {
if err == xsql.ErrNoRows {
err = nil
} else {
log.Error("RawUsersMid:row.Scan error(%v)", err)
}
}
return
}
// RawUsersKey get users by key
func (d *Dao) RawUsersKey(c context.Context, key string) (res *bwsmdl.Users, err error) {
res = &bwsmdl.Users{}
row := d.db.QueryRow(c, _usersKeySQL, key)
if err = row.Scan(&res.ID, &res.Mid, &res.Key, &res.Ctime, &res.Mtime, &res.Bid); err != nil {
if err == xsql.ErrNoRows {
err = nil
} else {
log.Error("RawUsersKey:row.Scan error(%v)", err)
}
}
return
}
// Binding binding mid
func (d *Dao) Binding(c context.Context, loginMid int64, p *bwsmdl.ParamBinding) (err error) {
if _, err = d.db.Exec(c, _bindingSQL, loginMid, p.Key); err != nil {
log.Error("Binding: db.Exec(%d,%s) error(%v)", loginMid, p.Key, err)
}
return
}
// UserByID .
func (d *Dao) UserByID(c context.Context, keyID int64) (res *bwsmdl.Users, err error) {
res = &bwsmdl.Users{}
row := d.db.QueryRow(c, _usersIDSQL, keyID)
if err = row.Scan(&res.ID, &res.Mid, &res.Key, &res.Ctime, &res.Mtime, &res.Bid); err != nil {
if err == xsql.ErrNoRows {
err = nil
} else {
log.Error("UserByID:row.Scan error(%v)", err)
}
}
return
}

View File

@@ -0,0 +1,82 @@
package bws
import (
"context"
"flag"
"path/filepath"
"testing"
"go-common/app/interface/main/activity/conf"
"go-common/app/interface/main/activity/model/bws"
. "github.com/smartystreets/goconvey/convey"
)
var d *Dao
func WithDao(f func(d *Dao)) func() {
return func() {
dir, _ := filepath.Abs("../../cmd/activity-test.toml")
flag.Set("conf", dir)
if err := conf.Init(); err != nil {
panic(err)
}
if d == nil {
d = New(conf.Conf)
}
f(d)
}
}
func TestDao_Binding(t *testing.T) {
Convey("test binding", t, WithDao(func(d *Dao) {
key := "9875fa517967622b"
err := d.Binding(context.Background(), 908087, &bws.ParamBinding{Key: key})
So(err, ShouldBeNil)
}))
}
func TestDao_UsersKey(t *testing.T) {
Convey("test users key", t, WithDao(func(d *Dao) {
key := "9875fa517967622b"
data, err := d.UsersKey(context.Background(), key)
So(err, ShouldBeNil)
Printf("%+v", data)
}))
}
func TestDao_UsersMid(t *testing.T) {
Convey("test users mid", t, WithDao(func(d *Dao) {
mid := int64(908087)
data, err := d.UsersMid(context.Background(), mid)
So(err, ShouldBeNil)
Printf("%+v", data)
}))
}
func TestDao_CacheUsersMid(t *testing.T) {
Convey("test cache users mid", t, WithDao(func(d *Dao) {
mid := int64(908087)
data, err := d.CacheUsersMid(context.Background(), mid)
So(err, ShouldBeNil)
Printf("%+v", data)
}))
}
func TestDao_DelCacheUsersMid(t *testing.T) {
Convey("test delete users mid", t, WithDao(func(d *Dao) {
mid := int64(908087)
err := d.DelCacheUsersMid(context.Background(), mid)
So(err, ShouldBeNil)
}))
}
func TestDao_RawUsersKey(t *testing.T) {
Convey("test users mid", t, WithDao(func(d *Dao) {
keyID := int64(1)
data, err := d.UserByID(context.Background(), keyID)
So(err, ShouldBeNil)
Printf("%+v", data)
}))
}

View File

@@ -0,0 +1,69 @@
package bws
import (
"context"
"fmt"
bwsmdl "go-common/app/interface/main/activity/model/bws"
)
func midKey(id int64) string {
return fmt.Sprintf("u_m_%d", id)
}
func keyKey(key string) string {
return fmt.Sprintf("u_k_%s", key)
}
func pointsKey(id int64) string {
return fmt.Sprintf("b_p_%d", id)
}
func achievesKey(id int64) string {
return fmt.Sprintf("b_a_%d", id)
}
//go:generate $GOPATH/src/go-common/app/tool/cache/gen
type _cache interface {
//cache: -sync=true
UsersMid(c context.Context, key int64) (*bwsmdl.Users, error)
//cache: -sync=true
UsersKey(c context.Context, key string) (*bwsmdl.Users, error)
//cache: -sync=true
Points(c context.Context, bid int64) (*bwsmdl.Points, error)
//cache: -sync=true
Achievements(c context.Context, bid int64) (*bwsmdl.Achievements, error)
//cache: -sync=true
UserAchieves(c context.Context, bid int64, key string) ([]*bwsmdl.UserAchieve, error)
//cache: -sync=true
UserPoints(c context.Context, bid int64, key string) ([]*bwsmdl.UserPoint, error)
//cache: -sync=true
AchieveCounts(c context.Context, bid int64, day string) ([]*bwsmdl.CountAchieves, error)
}
//go:generate $GOPATH/src/go-common/app/tool/cache/mc
type _mc interface {
//mc: -key=midKey
CacheUsersMid(c context.Context, key int64) (*bwsmdl.Users, error)
//mc: -key=midKey -expire=d.mcExpire -encode=pb
AddCacheUsersMid(c context.Context, key int64, value *bwsmdl.Users) error
//mc: -key=midKey
DelCacheUsersMid(c context.Context, key int64) error
//mc: -key=keyKey
CacheUsersKey(c context.Context, key string) (*bwsmdl.Users, error)
//mc: -key=keyKey -expire=d.mcExpire -encode=pb
AddCacheUsersKey(c context.Context, key string, value *bwsmdl.Users) error
//mc: -key=keyKey
DelCacheUsersKey(c context.Context, key string) error
//mc: -key=pointsKey
CachePoints(c context.Context, key int64) (*bwsmdl.Points, error)
//mc: -key=pointsKey -expire=d.mcExpire -encode=pb
AddCachePoints(c context.Context, key int64, value *bwsmdl.Points) error
//mc: -key=pointsKey
DelCachePoints(c context.Context, key int64) error
//mc: -key=achievesKey
CacheAchievements(c context.Context, key int64) (*bwsmdl.Achievements, error)
//mc: -key=achievesKey -expire=d.mcExpire -encode=pb
AddCacheAchievements(c context.Context, key int64, value *bwsmdl.Achievements) error
//mc: -key=achievesKey
DelCacheAchievements(c context.Context, key int64) error
}

View File

@@ -0,0 +1,208 @@
// Code generated by $GOPATH/src/go-common/app/tool/cache/gen. DO NOT EDIT.
/*
Package bws is a generated cache proxy package.
It is generated from:
type _cache interface {
//cache: -sync=true
UsersMid(c context.Context, key int64) (*bwsmdl.Users, error)
//cache: -sync=true
UsersKey(c context.Context, key string) (*bwsmdl.Users, error)
//cache: -sync=true
Points(c context.Context, bid int64) (*bwsmdl.Points, error)
//cache: -sync=true
Achievements(c context.Context, bid int64) (*bwsmdl.Achievements, error)
//cache: -sync=true
UserAchieves(c context.Context, bid int64, key string) ([]*bwsmdl.UserAchieve, error)
//cache: -sync=true
UserPoints(c context.Context, bid int64, key string) ([]*bwsmdl.UserPoint, error)
//cache: -sync=true
AchieveCounts(c context.Context, bid int64, day string) ([]*bwsmdl.CountAchieves, error)
}
*/
package bws
import (
"context"
bwsmdl "go-common/app/interface/main/activity/model/bws"
"go-common/library/stat/prom"
)
var _ _cache
// UsersMid get data from cache if miss will call source method, then add to cache.
func (d *Dao) UsersMid(c context.Context, id int64) (res *bwsmdl.Users, err error) {
addCache := true
res, err = d.CacheUsersMid(c, id)
if err != nil {
addCache = false
err = nil
}
if res != nil {
prom.CacheHit.Incr("UsersMid")
return
}
prom.CacheMiss.Incr("UsersMid")
res, err = d.RawUsersMid(c, id)
if err != nil {
return
}
miss := res
if !addCache {
return
}
d.AddCacheUsersMid(c, id, miss)
return
}
// UsersKey get data from cache if miss will call source method, then add to cache.
func (d *Dao) UsersKey(c context.Context, id string) (res *bwsmdl.Users, err error) {
addCache := true
res, err = d.CacheUsersKey(c, id)
if err != nil {
addCache = false
err = nil
}
if res != nil {
prom.CacheHit.Incr("UsersKey")
return
}
prom.CacheMiss.Incr("UsersKey")
res, err = d.RawUsersKey(c, id)
if err != nil {
return
}
miss := res
if !addCache {
return
}
d.AddCacheUsersKey(c, id, miss)
return
}
// Points get data from cache if miss will call source method, then add to cache.
func (d *Dao) Points(c context.Context, id int64) (res *bwsmdl.Points, err error) {
addCache := true
res, err = d.CachePoints(c, id)
if err != nil {
addCache = false
err = nil
}
if res != nil {
prom.CacheHit.Incr("Points")
return
}
prom.CacheMiss.Incr("Points")
res, err = d.RawPoints(c, id)
if err != nil {
return
}
miss := res
if !addCache {
return
}
d.AddCachePoints(c, id, miss)
return
}
// Achievements get data from cache if miss will call source method, then add to cache.
func (d *Dao) Achievements(c context.Context, id int64) (res *bwsmdl.Achievements, err error) {
addCache := true
res, err = d.CacheAchievements(c, id)
if err != nil {
addCache = false
err = nil
}
if res != nil {
prom.CacheHit.Incr("Achievements")
return
}
prom.CacheMiss.Incr("Achievements")
res, err = d.RawAchievements(c, id)
if err != nil {
return
}
miss := res
if !addCache {
return
}
d.AddCacheAchievements(c, id, miss)
return
}
// UserAchieves get data from cache if miss will call source method, then add to cache.
func (d *Dao) UserAchieves(c context.Context, id int64, key string) (res []*bwsmdl.UserAchieve, err error) {
addCache := true
res, err = d.CacheUserAchieves(c, id, key)
if err != nil {
addCache = false
err = nil
}
if len(res) != 0 {
prom.CacheHit.Incr("UserAchieves")
return
}
prom.CacheMiss.Incr("UserAchieves")
res, err = d.RawUserAchieves(c, id, key)
if err != nil {
return
}
miss := res
if !addCache {
return
}
d.AddCacheUserAchieves(c, id, miss, key)
return
}
// UserPoints get data from cache if miss will call source method, then add to cache.
func (d *Dao) UserPoints(c context.Context, id int64, key string) (res []*bwsmdl.UserPoint, err error) {
addCache := true
res, err = d.CacheUserPoints(c, id, key)
if err != nil {
addCache = false
err = nil
}
if len(res) != 0 {
prom.CacheHit.Incr("UserPoints")
return
}
prom.CacheMiss.Incr("UserPoints")
res, err = d.RawUserPoints(c, id, key)
if err != nil {
return
}
miss := res
if !addCache {
return
}
d.AddCacheUserPoints(c, id, miss, key)
return
}
// AchieveCounts get data from cache if miss will call source method, then add to cache.
func (d *Dao) AchieveCounts(c context.Context, id int64, day string) (res []*bwsmdl.CountAchieves, err error) {
addCache := true
res, err = d.CacheAchieveCounts(c, id, day)
if err != nil {
addCache = false
err = nil
}
if len(res) != 0 {
prom.CacheHit.Incr("AchieveCounts")
return
}
prom.CacheMiss.Incr("AchieveCounts")
res, err = d.RawAchieveCounts(c, id, day)
if err != nil {
return
}
miss := res
if !addCache {
return
}
d.AddCacheAchieveCounts(c, id, miss, day)
return
}

View File

@@ -0,0 +1,282 @@
// Code generated by $GOPATH/src/go-common/app/tool/cache/mc. DO NOT EDIT.
/*
Package bws is a generated mc cache package.
It is generated from:
type _mc interface {
//mc: -key=midKey
CacheUsersMid(c context.Context, key int64) (*bwsmdl.Users, error)
//mc: -key=midKey -expire=d.mcExpire -encode=pb
AddCacheUsersMid(c context.Context, key int64, value *bwsmdl.Users) error
//mc: -key=midKey
DelCacheUsersMid(c context.Context, key int64) error
//mc: -key=keyKey
CacheUsersKey(c context.Context, key string) (*bwsmdl.Users, error)
//mc: -key=keyKey -expire=d.mcExpire -encode=pb
AddCacheUsersKey(c context.Context, key string, value *bwsmdl.Users) error
//mc: -key=keyKey
DelCacheUsersKey(c context.Context, key string) error
//mc: -key=pointsKey
CachePoints(c context.Context, key int64) (*bwsmdl.Points, error)
//mc: -key=pointsKey -expire=d.mcExpire -encode=pb
AddCachePoints(c context.Context, key int64, value *bwsmdl.Points) error
//mc: -key=pointsKey
DelCachePoints(c context.Context, key int64) error
//mc: -key=achievesKey
CacheAchievements(c context.Context, key int64) (*bwsmdl.Achievements, error)
//mc: -key=achievesKey -expire=d.mcExpire -encode=pb
AddCacheAchievements(c context.Context, key int64, value *bwsmdl.Achievements) error
//mc: -key=achievesKey
DelCacheAchievements(c context.Context, key int64) error
}
*/
package bws
import (
"context"
"fmt"
bwsmdl "go-common/app/interface/main/activity/model/bws"
"go-common/library/cache/memcache"
"go-common/library/log"
"go-common/library/stat/prom"
)
var _ _mc
// CacheUsersMid get data from mc
func (d *Dao) CacheUsersMid(c context.Context, id int64) (res *bwsmdl.Users, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := midKey(id)
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheUsersMid")
log.Errorv(c, log.KV("CacheUsersMid", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = &bwsmdl.Users{}
err = conn.Scan(reply, res)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheUsersMid")
log.Errorv(c, log.KV("CacheUsersMid", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// AddCacheUsersMid Set data to mc
func (d *Dao) AddCacheUsersMid(c context.Context, id int64, val *bwsmdl.Users) (err error) {
if val == nil {
return
}
conn := d.mc.Get(c)
defer conn.Close()
key := midKey(id)
item := &memcache.Item{Key: key, Object: val, Expiration: d.mcExpire, Flags: memcache.FlagProtobuf}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheUsersMid")
log.Errorv(c, log.KV("AddCacheUsersMid", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// DelCacheUsersMid delete data from mc
func (d *Dao) DelCacheUsersMid(c context.Context, id int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := midKey(id)
if err = conn.Delete(key); err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:DelCacheUsersMid")
log.Errorv(c, log.KV("DelCacheUsersMid", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// CacheUsersKey get data from mc
func (d *Dao) CacheUsersKey(c context.Context, id string) (res *bwsmdl.Users, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := keyKey(id)
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheUsersKey")
log.Errorv(c, log.KV("CacheUsersKey", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = &bwsmdl.Users{}
err = conn.Scan(reply, res)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheUsersKey")
log.Errorv(c, log.KV("CacheUsersKey", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// AddCacheUsersKey Set data to mc
func (d *Dao) AddCacheUsersKey(c context.Context, id string, val *bwsmdl.Users) (err error) {
if val == nil {
return
}
conn := d.mc.Get(c)
defer conn.Close()
key := keyKey(id)
item := &memcache.Item{Key: key, Object: val, Expiration: d.mcExpire, Flags: memcache.FlagProtobuf}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheUsersKey")
log.Errorv(c, log.KV("AddCacheUsersKey", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// DelCacheUsersKey delete data from mc
func (d *Dao) DelCacheUsersKey(c context.Context, id string) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := keyKey(id)
if err = conn.Delete(key); err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:DelCacheUsersKey")
log.Errorv(c, log.KV("DelCacheUsersKey", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// CachePoints get data from mc
func (d *Dao) CachePoints(c context.Context, id int64) (res *bwsmdl.Points, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := pointsKey(id)
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CachePoints")
log.Errorv(c, log.KV("CachePoints", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = &bwsmdl.Points{}
err = conn.Scan(reply, res)
if err != nil {
prom.BusinessErrCount.Incr("mc:CachePoints")
log.Errorv(c, log.KV("CachePoints", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// AddCachePoints Set data to mc
func (d *Dao) AddCachePoints(c context.Context, id int64, val *bwsmdl.Points) (err error) {
if val == nil {
return
}
conn := d.mc.Get(c)
defer conn.Close()
key := pointsKey(id)
item := &memcache.Item{Key: key, Object: val, Expiration: d.mcExpire, Flags: memcache.FlagProtobuf}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCachePoints")
log.Errorv(c, log.KV("AddCachePoints", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// DelCachePoints delete data from mc
func (d *Dao) DelCachePoints(c context.Context, id int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := pointsKey(id)
if err = conn.Delete(key); err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:DelCachePoints")
log.Errorv(c, log.KV("DelCachePoints", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// CacheAchievements get data from mc
func (d *Dao) CacheAchievements(c context.Context, id int64) (res *bwsmdl.Achievements, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := achievesKey(id)
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheAchievements")
log.Errorv(c, log.KV("CacheAchievements", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = &bwsmdl.Achievements{}
err = conn.Scan(reply, res)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheAchievements")
log.Errorv(c, log.KV("CacheAchievements", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// AddCacheAchievements Set data to mc
func (d *Dao) AddCacheAchievements(c context.Context, id int64, val *bwsmdl.Achievements) (err error) {
if val == nil {
return
}
conn := d.mc.Get(c)
defer conn.Close()
key := achievesKey(id)
item := &memcache.Item{Key: key, Object: val, Expiration: d.mcExpire, Flags: memcache.FlagProtobuf}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheAchievements")
log.Errorv(c, log.KV("AddCacheAchievements", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// DelCacheAchievements delete data from mc
func (d *Dao) DelCacheAchievements(c context.Context, id int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := achievesKey(id)
if err = conn.Delete(key); err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:DelCacheAchievements")
log.Errorv(c, log.KV("DelCacheAchievements", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}

View File

@@ -0,0 +1,200 @@
package bws
import (
"context"
"database/sql"
"encoding/json"
"fmt"
bwsmdl "go-common/app/interface/main/activity/model/bws"
"go-common/library/cache/redis"
xsql "go-common/library/database/sql"
"go-common/library/log"
)
const (
_userPointKeyFmt = "bws_u_p_%d_%s"
_pointsSQL = "SELECT id,`name`,icon,fid,image,unlocked,lock_type,dic,rule,bid,lose_unlocked,other_ip,ower,ctime,mtime FROM act_bws_points WHERE del = 0 AND bid = ? ORDER BY ID"
_userPointSQL = "SELECT id,pid,points,ctime FROM act_bws_user_points WHERE bid = ? AND `key` = ? AND del = 0"
_userPointAddSQL = "INSERT INTO act_bws_user_points(bid,pid,points,`key`) VALUES(?,?,?,?)"
)
func keyUserPoint(bid int64, key string) string {
return fmt.Sprintf(_userPointKeyFmt, bid, key)
}
// RawPoints points list
func (d *Dao) RawPoints(c context.Context, bid int64) (res *bwsmdl.Points, err error) {
var (
rows *xsql.Rows
rs []*bwsmdl.Point
)
if rows, err = d.db.Query(c, _pointsSQL, bid); err != nil {
log.Error("RawPoints: db.Exec(%d) error(%v)", bid, err)
return
}
defer rows.Close()
for rows.Next() {
r := new(bwsmdl.Point)
if err = rows.Scan(&r.ID, &r.Name, &r.Icon, &r.Fid, &r.Image, &r.Unlocked, &r.LockType, &r.Dic, &r.Rule, &r.Bid, &r.LoseUnlocked, &r.OtherIp, &r.Ower, &r.Ctime, &r.Mtime); err != nil {
log.Error("RawPoints:row.Scan() error(%v)", err)
return
}
rs = append(rs, r)
}
if len(rs) > 0 {
res = new(bwsmdl.Points)
res.Points = rs
}
return
}
// RawUserPoints .
func (d *Dao) RawUserPoints(c context.Context, bid int64, key string) (rs []*bwsmdl.UserPoint, err error) {
var (
rows *xsql.Rows
)
if rows, err = d.db.Query(c, _userPointSQL, bid, key); err != nil {
log.Error("RawUserPoints:db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
r := new(bwsmdl.UserPoint)
if err = rows.Scan(&r.ID, &r.Pid, &r.Points, &r.Ctime); err != nil {
log.Error("RawUserPoints:row.Scan() error(%v)", err)
return
}
rs = append(rs, r)
}
return
}
// AddUserPoint .
func (d *Dao) AddUserPoint(c context.Context, bid, pid, points int64, key string) (lastID int64, err error) {
var res sql.Result
if res, err = d.db.Exec(c, _userPointAddSQL, bid, pid, points, key); err != nil {
log.Error("AddUserPoint error d.db.Exec(%d,%d,%d,%s) error(%v)", bid, pid, points, key, err)
return
}
return res.LastInsertId()
}
// CacheUserPoints .
func (d *Dao) CacheUserPoints(c context.Context, bid int64, key string) (res []*bwsmdl.UserPoint, err error) {
var (
values []interface{}
cacheKey = keyUserPoint(bid, key)
conn = d.redis.Get(c)
)
defer conn.Close()
if values, err = redis.Values(conn.Do("ZRANGE", cacheKey, 0, -1)); err != nil {
log.Error("CacheUserAchieves conn.Do(ZRANGE, %s) error(%v)", cacheKey, err)
return
} else if len(values) == 0 {
return
}
for len(values) > 0 {
var bs []byte
if values, err = redis.Scan(values, &bs); err != nil {
log.Error("CacheUserAchieves redis.Scan(%v) error(%v)", values, err)
return
}
item := new(bwsmdl.UserPoint)
if err = json.Unmarshal(bs, &item); err != nil {
log.Error("CacheUserAchieves conn.Do(ZRANGE, %s) error(%v)", cacheKey, err)
continue
}
res = append(res, item)
}
return
}
// AddCacheUserPoints .
func (d *Dao) AddCacheUserPoints(c context.Context, bid int64, data []*bwsmdl.UserPoint, key string) (err error) {
var bs []byte
if len(data) == 0 {
return
}
cacheKey := keyUserPoint(bid, key)
conn := d.redis.Get(c)
defer conn.Close()
args := redis.Args{}.Add(cacheKey)
for _, v := range data {
if bs, err = json.Marshal(v); err != nil {
log.Error("AddCacheUserPoints json.Marshal() error(%v)", err)
return
}
args = args.Add(v.ID).Add(bs)
}
if err = conn.Send("ZADD", args...); err != nil {
log.Error("AddCacheUserPoints conn.Send(ZADD, %s, %v) error(%v)", cacheKey, args, err)
return
}
if err = conn.Send("EXPIRE", cacheKey, d.userPointExpire); err != nil {
log.Error("AddCacheUserPoints conn.Send(Expire, %s) error(%v)", cacheKey, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("AddCacheUserPoints conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("AddCacheUserPoints conn.Receive() error(%v)", err)
return
}
}
return
}
// AppendUserPointsCache .
func (d *Dao) AppendUserPointsCache(c context.Context, bid int64, key string, point *bwsmdl.UserPoint) (err error) {
var (
bs []byte
ok bool
cacheKey = keyUserPoint(bid, key)
conn = d.redis.Get(c)
)
defer conn.Close()
if ok, err = redis.Bool(conn.Do("EXPIRE", cacheKey, d.userPointExpire)); err != nil || !ok {
log.Error("AppendUserPointsCache conn.Do(EXPIRE %s) error(%v)", key, err)
return
}
args := redis.Args{}.Add(cacheKey)
if bs, err = json.Marshal(point); err != nil {
log.Error("AppendUserPointsCache json.Marshal() error(%v)", err)
return
}
args = args.Add(point.ID).Add(bs)
if err = conn.Send("ZADD", args...); err != nil {
log.Error("AppendUserPointsCache conn.Send(ZADD, %s, %v) error(%v)", cacheKey, args, err)
return
}
if err = conn.Send("EXPIRE", cacheKey, d.userPointExpire); err != nil {
log.Error("AppendUserPointsCache conn.Send(Expire, %s) error(%v)", cacheKey, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("AppendUserPointsCache conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("AppendUserPointsCache conn.Receive() error(%v)", err)
return
}
}
return
}
// DelCacheUserPoints .
func (d *Dao) DelCacheUserPoints(c context.Context, bid int64, key string) (err error) {
cacheKey := keyUserPoint(bid, key)
conn := d.redis.Get(c)
defer conn.Close()
if _, err = conn.Do("DEL", cacheKey); err != nil {
log.Error("DelCacheUserPoints conn.Do(DEL) key(%s) error(%v)", cacheKey, err)
}
return
}

View File

@@ -0,0 +1,48 @@
package bws
import (
"context"
"encoding/json"
"testing"
"time"
"go-common/app/interface/main/activity/model/bws"
xtime "go-common/library/time"
. "github.com/smartystreets/goconvey/convey"
)
func TestDao_RawUserPoints(t *testing.T) {
Convey("test cache user points", t, WithDao(func(d *Dao) {
bid := int64(3)
key := "9875fa517967622b"
data, err := d.RawUserPoints(context.Background(), bid, key)
So(err, ShouldBeNil)
bs, _ := json.Marshal(data)
Println(string(bs))
}))
}
func TestDao_CacheUserPoints(t *testing.T) {
Convey("test cache user points", t, WithDao(func(d *Dao) {
bid := int64(3)
key := "9875fa517967622b"
data, err := d.CacheUserPoints(context.Background(), bid, key)
So(err, ShouldBeNil)
bs, _ := json.Marshal(data)
Println(string(bs))
}))
}
func TestDao_AddCacheUserPoints(t *testing.T) {
Convey("add user points cache", t, WithDao(func(d *Dao) {
bid := int64(3)
key := "9875fa517967622b"
data := []*bws.UserPoint{
{ID: 1, Pid: 2, Points: 3, Ctime: xtime.Time(time.Now().Unix())},
{ID: 2, Pid: 3, Points: 4, Ctime: xtime.Time(time.Now().Unix())},
}
err := d.AddCacheUserPoints(context.Background(), bid, data, key)
So(err, ShouldBeNil)
}))
}

View File

@@ -0,0 +1,65 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = [
"cache.go",
"dao.cache.go",
"dao.go",
"kfc.go",
"mc.cache.go",
],
importpath = "go-common/app/interface/main/activity/dao/kfc",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/activity/conf:go_default_library",
"//app/interface/main/activity/model/kfc:go_default_library",
"//library/cache/memcache:go_default_library",
"//library/database/sql:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/net/metadata:go_default_library",
"//library/stat/prom:go_default_library",
"//vendor/github.com/pkg/errors:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)
go_test(
name = "go_default_test",
srcs = [
"cache_test.go",
"dao.cache_test.go",
"dao_test.go",
"kfc_test.go",
"mc.cache_test.go",
],
embed = [":go_default_library"],
tags = ["automanaged"],
deps = [
"//app/interface/main/activity/conf:go_default_library",
"//app/interface/main/activity/model/kfc:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)

View File

@@ -0,0 +1,36 @@
package kfc
import (
"context"
"fmt"
"go-common/app/interface/main/activity/model/kfc"
)
func kfcKey(id int64) string {
return fmt.Sprintf("b_kfc_c_%d", id)
}
func kfcCodeKey(code string) string {
return fmt.Sprintf("b_kfc_code_%s", code)
}
//go:generate $GOPATH/src/go-common/app/tool/cache/gen
type _cache interface {
// cache: -sync=true
KfcCoupon(c context.Context, id int64) (*kfc.BnjKfcCoupon, error)
}
//go:generate $GOPATH/src/go-common/app/tool/cache/mc
type _mc interface {
// mc: -key=kfcKey
CacheKfcCoupon(c context.Context, id int64) (*kfc.BnjKfcCoupon, error)
// mc: -key=kfcKey -expire=d.mcKfcExpire -encode=pb
AddCacheKfcCoupon(c context.Context, id int64, val *kfc.BnjKfcCoupon) error
// mc: -key=kfcKey
DelCacheKfcCoupon(c context.Context, id int64) error
// mc: -key=kfcCodeKey
CacheKfcCode(c context.Context, code string) (int64, error)
// mc: -key=kfcCodeKey -expire=d.mcKfcCodeExpire -encode=raw
AddCacheKfcCode(c context.Context, code string, val int64) error
}

View File

@@ -0,0 +1,35 @@
package kfc
import (
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestKfckfcKey(t *testing.T) {
convey.Convey("kfcKey", t, func(convCtx convey.C) {
var (
id = int64(3)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := kfcKey(id)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestKfckfcCodeKey(t *testing.T) {
convey.Convey("kfcCodeKey", t, func(convCtx convey.C) {
var (
code = "201812041201"
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := kfcCodeKey(code)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,46 @@
// Code generated by $GOPATH/src/go-common/app/tool/cache/gen. DO NOT EDIT.
/*
Package kfc is a generated cache proxy package.
It is generated from:
type _cache interface {
// cache: -sync=true
KfcCoupon(c context.Context, id int64) (*kfc.BnjKfcCoupon, error)
}
*/
package kfc
import (
"context"
"go-common/app/interface/main/activity/model/kfc"
"go-common/library/stat/prom"
)
var _ _cache
// KfcCoupon get data from cache if miss will call source method, then add to cache.
func (d *Dao) KfcCoupon(c context.Context, id int64) (res *kfc.BnjKfcCoupon, err error) {
addCache := true
res, err = d.CacheKfcCoupon(c, id)
if err != nil {
addCache = false
err = nil
}
if res != nil {
prom.CacheHit.Incr("KfcCoupon")
return
}
prom.CacheMiss.Incr("KfcCoupon")
res, err = d.RawKfcCoupon(c, id)
if err != nil {
return
}
miss := res
if !addCache {
return
}
d.AddCacheKfcCoupon(c, id, miss)
return
}

View File

@@ -0,0 +1,24 @@
package kfc
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestKfcKfcCoupon(t *testing.T) {
convey.Convey("KfcCoupon", t, func(convCtx convey.C) {
var (
c = context.Background()
id = int64(3)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
res, err := d.KfcCoupon(c, id)
convCtx.Convey("Then err should be nil.res should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(res, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,55 @@
package kfc
import (
"time"
"go-common/app/interface/main/activity/conf"
"go-common/library/cache/memcache"
xsql "go-common/library/database/sql"
"go-common/library/log"
httpx "go-common/library/net/http/blademaster"
"go-common/library/stat/prom"
)
const (
_kfcWinnerURI = "/gift/v4/Smalltv/getKfcWinnerById"
)
// PromError stat and log.
func PromError(name string, format string, args ...interface{}) {
prom.BusinessErrCount.Incr(name)
log.Error(format, args...)
}
// Dao dao.
type Dao struct {
mc *memcache.Pool
db *xsql.DB
client *httpx.Client
mcKfcExpire int32
mcKfcCodeExpire int32
kfcWinnerURL string
}
// New dao new.
func New(c *conf.Config) (d *Dao) {
d = &Dao{
mc: memcache.NewPool(c.Memcache.Like),
db: xsql.NewMySQL(c.MySQL.Like),
client: httpx.NewClient(c.HTTPClientKfc),
mcKfcExpire: int32(time.Duration(c.Memcache.KfcExpire) / time.Second),
mcKfcCodeExpire: int32(time.Duration(c.Memcache.KfcCodeExpire) / time.Second),
kfcWinnerURL: c.Host.LiveCo + _kfcWinnerURI,
}
return
}
// Close Dao
func (d *Dao) Close() {
if d.db != nil {
d.db.Close()
}
if d.mc != nil {
d.mc.Close()
}
}

View File

@@ -0,0 +1,35 @@
package kfc
import (
"flag"
"os"
"testing"
"go-common/app/interface/main/activity/conf"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.web-svr.activity")
flag.Set("conf_token", "22edc93e2998bf0cb0bbee661b03d41f")
flag.Set("tree_id", "2873")
flag.Set("conf_version", "docker-1")
flag.Set("deploy_env", "uat")
flag.Set("conf_host", "config.bilibili.co")
flag.Set("conf_path", "/tmp")
flag.Set("region", "sh")
flag.Set("zone", "sh001")
} else {
flag.Set("conf", "../../cmd/activity-test.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
os.Exit(m.Run())
}

View File

@@ -0,0 +1,99 @@
package kfc
import (
"context"
"database/sql"
"net/url"
"strconv"
"go-common/app/interface/main/activity/model/kfc"
xsql "go-common/library/database/sql"
"go-common/library/ecode"
"go-common/library/net/metadata"
"github.com/pkg/errors"
)
// KfcCodeUsed kfcDao const.
var (
KfcCodeUsed = 1
KfcCodeNotGiveOut = 0
_kfcCouponSQL = "select `id`,`mid`,`ctime`,`mtime`,`coupon_code`,`desc`,`state`,`delete_time` from bnj_kfc_coupon where id = ?"
_kfcCodeSQL = "select `id`,`mid`,`ctime`,`mtime`,`coupon_code`,`desc`,`state`,`delete_time` from bnj_kfc_coupon where coupon_code = ?"
_kfcCodeGiveOuteSQL = "update `bnj_kfc_coupon` set `state` = ? where `id` = ? and `state` = ?"
_kfcDeliverSQL = "update `bnj_kfc_coupon` set mid = ? where id = ? and mid = 0"
)
// RawKfcCoupon get coupon .
func (d *Dao) RawKfcCoupon(c context.Context, id int64) (res *kfc.BnjKfcCoupon, err error) {
res = &kfc.BnjKfcCoupon{}
row := d.db.QueryRow(c, _kfcCouponSQL, id)
if err = row.Scan(&res.ID, &res.Mid, &res.Ctime, &res.Mtime, &res.CouponCode, &res.Desc, &res.State, &res.DeleteTime); err != nil {
if err == xsql.ErrNoRows {
err = nil
} else {
err = errors.Wrap(err, "RawKfcCoupon:row.Scan()")
}
}
return
}
// RawKfcCode .
func (d *Dao) RawKfcCode(c context.Context, code string) (res *kfc.BnjKfcCoupon, err error) {
res = &kfc.BnjKfcCoupon{}
row := d.db.QueryRow(c, _kfcCodeSQL, code)
if err = row.Scan(&res.ID, &res.Mid, &res.Ctime, &res.Mtime, &res.CouponCode, &res.Desc, &res.State, &res.DeleteTime); err != nil {
if err == xsql.ErrNoRows {
err = nil
} else {
err = errors.Wrap(err, "RawKfcCode:row.Scan()")
}
}
return
}
// KfcCodeGiveOut .
func (d *Dao) KfcCodeGiveOut(c context.Context, id int64) (res int64, err error) {
var (
sqlRes sql.Result
)
if sqlRes, err = d.db.Exec(c, _kfcCodeGiveOuteSQL, KfcCodeUsed, id, KfcCodeNotGiveOut); err != nil {
err = errors.Wrap(err, "d.db.Exec()")
return
}
return sqlRes.RowsAffected()
}
// KfcDeliver .
func (d *Dao) KfcDeliver(c context.Context, id, mid int64) (res int64, err error) {
var (
sqlRes sql.Result
)
if sqlRes, err = d.db.Exec(c, _kfcDeliverSQL, mid, id); err != nil {
err = errors.Wrap(err, "d.db.Exec()")
return
}
return sqlRes.RowsAffected()
}
// KfcWinner .
func (d *Dao) KfcWinner(c context.Context, id int64) (uid int64, err error) {
params := url.Values{}
params.Set("id", strconv.FormatInt(id, 10))
var res struct {
Code int `json:"code"`
Data struct {
UID int64 `json:"uid"`
} `json:"data"`
}
if err = d.client.Get(c, d.kfcWinnerURL, metadata.String(c, metadata.RemoteIP), params, &res); err != nil {
err = errors.Wrapf(err, "d.client.Get(%s)", d.kfcWinnerURL+"?"+params.Encode())
return
}
if res.Code != ecode.OK.Code() {
err = ecode.Int(res.Code)
return
}
uid = res.Data.UID
return
}

View File

@@ -0,0 +1,73 @@
package kfc
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestKfcRawKfcCoupon(t *testing.T) {
convey.Convey("RawKfcCoupon", t, func(convCtx convey.C) {
var (
c = context.Background()
id = int64(4)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
res, err := d.RawKfcCoupon(c, id)
convCtx.Convey("Then err should be nil.res should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestKfcRawKfcCode(t *testing.T) {
convey.Convey("RawKfcCode", t, func(convCtx convey.C) {
var (
c = context.Background()
code = "201812041203"
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
res, err := d.RawKfcCode(c, code)
convCtx.Convey("Then err should be nil.res should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestKfcKfcCodeGiveOut(t *testing.T) {
convey.Convey("KfcCodeGiveOut", t, func(convCtx convey.C) {
var (
c = context.Background()
id = int64(3)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
res, err := d.KfcCodeGiveOut(c, id)
convCtx.Convey("Then err should be nil.res should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestKfcDeliver(t *testing.T) {
convey.Convey("KfcCodeGiveOut", t, func(convCtx convey.C) {
var (
c = context.Background()
id = int64(3)
mid = int64(5874874)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
res, err := d.KfcDeliver(c, id, mid)
convCtx.Convey("Then err should be nil.res should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(res, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,139 @@
// Code generated by $GOPATH/src/go-common/app/tool/cache/mc. DO NOT EDIT.
/*
Package kfc is a generated mc cache package.
It is generated from:
type _mc interface {
// mc: -key=kfcKey
CacheKfcCoupon(c context.Context, id int64) (*kfc.BnjKfcCoupon, error)
// mc: -key=kfcKey -expire=d.mcKfcExpire -encode=pb
AddCacheKfcCoupon(c context.Context, id int64, val *kfc.BnjKfcCoupon) error
// mc: -key=kfcKey
DelCacheKfcCoupon(c context.Context, id int64) error
// mc: -key=kfcCodeKey
CacheKfcCode(c context.Context, code string) (int64, error)
// mc: -key=kfcCodeKey -expire=d.mcKfcCodeExpire -encode=raw
AddCacheKfcCode(c context.Context, code string, val int64) error
}
*/
package kfc
import (
"context"
"fmt"
"strconv"
"go-common/app/interface/main/activity/model/kfc"
"go-common/library/cache/memcache"
"go-common/library/log"
"go-common/library/stat/prom"
)
var _ _mc
// CacheKfcCoupon get data from mc
func (d *Dao) CacheKfcCoupon(c context.Context, id int64) (res *kfc.BnjKfcCoupon, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := kfcKey(id)
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheKfcCoupon")
log.Errorv(c, log.KV("CacheKfcCoupon", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = &kfc.BnjKfcCoupon{}
err = conn.Scan(reply, res)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheKfcCoupon")
log.Errorv(c, log.KV("CacheKfcCoupon", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// AddCacheKfcCoupon Set data to mc
func (d *Dao) AddCacheKfcCoupon(c context.Context, id int64, val *kfc.BnjKfcCoupon) (err error) {
if val == nil {
return
}
conn := d.mc.Get(c)
defer conn.Close()
key := kfcKey(id)
item := &memcache.Item{Key: key, Object: val, Expiration: d.mcKfcExpire, Flags: memcache.FlagProtobuf}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheKfcCoupon")
log.Errorv(c, log.KV("AddCacheKfcCoupon", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// DelCacheKfcCoupon delete data from mc
func (d *Dao) DelCacheKfcCoupon(c context.Context, id int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := kfcKey(id)
if err = conn.Delete(key); err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:DelCacheKfcCoupon")
log.Errorv(c, log.KV("DelCacheKfcCoupon", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// CacheKfcCode get data from mc
func (d *Dao) CacheKfcCode(c context.Context, id string) (res int64, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := kfcCodeKey(id)
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheKfcCode")
log.Errorv(c, log.KV("CacheKfcCode", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
var v string
err = conn.Scan(reply, &v)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheKfcCode")
log.Errorv(c, log.KV("CacheKfcCode", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
r, err := strconv.ParseInt(v, 10, 64)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheKfcCode")
log.Errorv(c, log.KV("CacheKfcCode", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = int64(r)
return
}
// AddCacheKfcCode Set data to mc
func (d *Dao) AddCacheKfcCode(c context.Context, id string, val int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := kfcCodeKey(id)
bs := []byte(strconv.FormatInt(int64(val), 10))
item := &memcache.Item{Key: key, Value: bs, Expiration: d.mcKfcCodeExpire, Flags: memcache.FlagRAW}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheKfcCode")
log.Errorv(c, log.KV("AddCacheKfcCode", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}

View File

@@ -0,0 +1,89 @@
package kfc
import (
"context"
"testing"
"go-common/app/interface/main/activity/model/kfc"
"github.com/smartystreets/goconvey/convey"
)
func TestKfcCacheKfcCoupon(t *testing.T) {
convey.Convey("CacheKfcCoupon", t, func(convCtx convey.C) {
var (
c = context.Background()
id = int64(3)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
res, err := d.CacheKfcCoupon(c, id)
convCtx.Convey("Then err should be nil.res should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestKfcAddCacheKfcCoupon(t *testing.T) {
convey.Convey("AddCacheKfcCoupon", t, func(convCtx convey.C) {
var (
c = context.Background()
id = int64(3)
val = &kfc.BnjKfcCoupon{ID: 3, CouponCode: "201812041201", Mid: 2089809}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.AddCacheKfcCoupon(c, id, val)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestKfcDelCacheKfcCoupon(t *testing.T) {
convey.Convey("DelCacheKfcCoupon", t, func(convCtx convey.C) {
var (
c = context.Background()
id = int64(3)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.DelCacheKfcCoupon(c, id)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestKfcCacheKfcCode(t *testing.T) {
convey.Convey("CacheKfcCode", t, func(convCtx convey.C) {
var (
c = context.Background()
id = "201812041201"
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
res, err := d.CacheKfcCode(c, id)
convCtx.Convey("Then err should be nil.res should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestKfcAddCacheKfcCode(t *testing.T) {
convey.Convey("AddCacheKfcCode", t, func(convCtx convey.C) {
var (
c = context.Background()
id = "201812041201"
val = int64(3)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.AddCacheKfcCode(c, id, val)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,102 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = [
"achievements_test.go",
"act_mission_test.go",
"act_test.go",
"action_test.go",
"cache_test.go",
"content_test.go",
"dao.cache_test.go",
"dao_test.go",
"extend_test.go",
"like_test.go",
"lottery_test.go",
"match_redis_test.go",
"match_test.go",
"mc.cache_test.go",
"memcached_test.go",
"mission_group_test.go",
"protocol_test.go",
"redis_test.go",
"subject_test.go",
"user_achievements_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/activity/conf:go_default_library",
"//app/interface/main/activity/model/like:go_default_library",
"//library/time:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"achievements.go",
"act.go",
"act_mission.go",
"action.go",
"cache.go",
"content.go",
"dao.cache.go",
"dao.go",
"extend.go",
"like.go",
"lottery.go",
"match.go",
"match_redis.go",
"mc.cache.go",
"memcached.go",
"mission_group.go",
"protocol.go",
"redis.go",
"subject.go",
"user_achievements.go",
],
importpath = "go-common/app/interface/main/activity/dao/like",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/activity/conf:go_default_library",
"//app/interface/main/activity/model/like:go_default_library",
"//library/cache/memcache:go_default_library",
"//library/cache/redis:go_default_library",
"//library/database/elastic:go_default_library",
"//library/database/sql:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/net/metadata:go_default_library",
"//library/stat/prom:go_default_library",
"//library/sync/pipeline/fanout:go_default_library",
"//library/time:go_default_library",
"//library/xstr:go_default_library",
"//vendor/github.com/pkg/errors:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,44 @@
package like
import (
"context"
likemdl "go-common/app/interface/main/activity/model/like"
xsql "go-common/library/database/sql"
"github.com/pkg/errors"
)
const (
_achievesSQL = "select `id`,`name`,`icon`,`dic`,`unlock`,`ctime`,`mtime`,`del`,`sid`,`image`,`award` from act_like_achievements where sid = ? and del = 0 order by `unlock` limit 100"
// HaveAward award state
HaveAward = 1
)
// RawActLikeAchieves .
func (d *Dao) RawActLikeAchieves(c context.Context, sid int64) (res *likemdl.Achievements, err error) {
var rows *xsql.Rows
if rows, err = d.db.Query(c, _achievesSQL, sid); err != nil {
if err == xsql.ErrNoRows {
err = nil
} else {
err = errors.Wrapf(err, "RawActLikeAchieves:Query(%s)", _achievesSQL)
return
}
}
defer rows.Close()
list := make([]*likemdl.ActLikeAchievement, 0, 100)
for rows.Next() {
a := &likemdl.ActLikeAchievement{}
if err = rows.Scan(&a.ID, &a.Name, &a.Icon, &a.Dic, &a.Unlock, &a.Ctime, &a.Mtime, &a.Del, &a.Sid, &a.Image, &a.Award); err != nil {
err = errors.Wrap(err, "RawActLikeAchieves:scan()")
return
}
list = append(list, a)
}
res = &likemdl.Achievements{Achievements: list}
if err = rows.Err(); err != nil {
err = errors.Wrap(err, "RawActLikeAchieves:rows.Err()")
}
return
}

View File

@@ -0,0 +1,23 @@
package like
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestLikeRawActLikeAchieves(t *testing.T) {
convey.Convey("RawActLikeAchieves", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10805)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.RawActLikeAchieves(c, sid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,59 @@
package like
import (
"context"
"fmt"
"go-common/library/cache/redis"
"github.com/pkg/errors"
)
const (
_redDotKeyFmt = "rd_%d"
)
func keyRedDot(mid int64) string {
return fmt.Sprintf(_redDotKeyFmt, mid)
}
// CacheRedDotTs .
func (d *Dao) CacheRedDotTs(c context.Context, mid int64) (ts int64, err error) {
key := keyRedDot(mid)
conn := d.redis.Get(c)
defer conn.Close()
if ts, err = redis.Int64(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
} else {
err = errors.Wrapf(err, "conn.Do(GET, %s)", key)
}
}
return
}
// AddCacheRedDotTs .
func (d *Dao) AddCacheRedDotTs(c context.Context, mid, ts int64) (err error) {
key := keyRedDot(mid)
conn := d.redis.Get(c)
defer conn.Close()
if err = conn.Send("SET", key, ts); err != nil {
err = errors.Wrapf(err, "conn.Send(SET, %s, %d)", key, ts)
return
}
if err = conn.Send("EXPIRE", key, d.hotDotExpire); err != nil {
err = errors.Wrapf(err, "conn.Send(EXPIRE, %s, %d)", key, ts)
return
}
if err = conn.Flush(); err != nil {
err = errors.Wrap(err, "AddCacheHotDotTs conn.Flush")
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
err = errors.Wrapf(err, "add conn.Receive(%d)", i+1)
return
}
}
return
}

View File

@@ -0,0 +1,233 @@
package like
import (
"context"
"database/sql"
"fmt"
l "go-common/app/interface/main/activity/model/like"
"go-common/library/cache/redis"
xsql "go-common/library/database/sql"
"go-common/library/log"
"github.com/pkg/errors"
)
const (
_likeActMissionItemSQL = "select id from like_act_mission_group where sid = ? and lid = ? and mid = ?"
_addLikeActMissionSQL = "insert into like_act_mission_group (`sid`,`mid`,`lid`,`action`,`ipv6`) values(?,?,?,?,?)"
_likeActMissionFriendsSQL = "select id,sid,lid,mid,action from like_act_mission_group where sid = ? and lid = ? order by id asc limit 100 "
_keyMissionLikeLimitFmt = "go:m:l:limt:%d:%d"
_keyMissionScoreFmt = "go:l:a:m:score:%d"
_keyMissionScoreStrFmt = "go:l:a:m:score:str:%d:%d"
_scoreMaxTime = 2145888000
_scoreMaxNum = 1000000
_maxMissionTop = 200
)
// missionLikeLimitKey .
func missionLikeLimitKey(sid, mid int64) string {
return fmt.Sprintf(_keyMissionLikeLimitFmt, sid, mid)
}
// likeActMissionScoreKey .
func likeActMissionScoreKey(sid int64) string {
return fmt.Sprintf(_keyMissionScoreFmt, sid)
}
// likeMissionScoreStrKey .
func likeMissionScoreStrKey(sid, lid int64) string {
return fmt.Sprintf(_keyMissionScoreStrFmt, sid, lid)
}
// scoreMaxTime .
func scoreMaxTime() int64 {
return _scoreMaxTime
}
// scoreMaxNum only for num lower 1 million.
func scoreMaxNum() int64 {
return _scoreMaxNum
}
// buildRankScore only for num lower 1 million.
func buildRankScore(num int64, ctime int64) int64 {
var (
maxTimeStamp = scoreMaxTime()
timeScore = maxTimeStamp - ctime
rankScore int64
)
rankScore = (num & 0xFFFFF) << 32
rankScore |= timeScore & 0xFFFFFFFF
return rankScore
}
// RawActMission .
func (d *Dao) RawActMission(c context.Context, sid, lid, mid int64) (res int64, err error) {
act := &l.ActMissionGroup{}
rows := d.db.QueryRow(c, _likeActMissionItemSQL, sid, lid, mid)
if err = rows.Scan(&act.ID); err != nil {
if err == xsql.ErrNoRows {
err = nil
} else {
err = errors.Wrap(err, "RawActMission:QueryRow")
return
}
}
res = act.ID
return
}
// MissionLikeLimit .
func (d *Dao) MissionLikeLimit(c context.Context, sid, mid int64) (res int64, err error) {
key := missionLikeLimitKey(sid, mid)
conn := d.redis.Get(c)
defer conn.Close()
if res, err = redis.Int64(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
} else {
err = errors.Wrapf(err, "conn.Do(GET, %s)", key)
}
}
return
}
// InrcMissionLikeLimit .
func (d *Dao) InrcMissionLikeLimit(c context.Context, sid, mid int64, val int64) (res bool, err error) {
key := missionLikeLimitKey(sid, mid)
conn := d.redis.Get(c)
defer conn.Close()
if res, err = redis.Bool(conn.Do("INCRBY", key, val)); err != nil {
log.Error("InrcMissionLikeLimit:conn.Do(INCR) %s %d", key, val)
}
return
}
// SetMissionTop .
func (d *Dao) SetMissionTop(c context.Context, sid, lid int64, score int64, ctime int64) (count int64, err error) {
var (
conn = d.redis.Get(c)
key = likeActMissionScoreKey(sid)
strKey = likeMissionScoreStrKey(sid, lid)
maxNum = scoreMaxNum()
rankScore int64
)
defer conn.Close()
if count, err = redis.Int64(conn.Do("INCRBY", strKey, score)); err != nil {
err = errors.Wrap(err, "conn.Do(INCRBY)")
return
}
// the score could not more than 1 million
if count > maxNum {
log.Warn("SetMissionTop over max score (%d) error", count)
return
}
rankScore = buildRankScore(count, ctime)
// set top list
if _, err = redis.Bool(conn.Do("ZADD", key, rankScore, lid)); err != nil {
err = errors.Wrapf(err, "conn.Do(ZADD) key(%s)", key)
return
}
if _, err = conn.Do("ZREMRANGEBYRANK", key, 0, -(_maxMissionTop + 1)); err != nil {
err = errors.Wrapf(err, "conn.Do(ZREMRANGEBYRANK) key(%s)", key)
}
return
}
// MissionLidScore .
func (d *Dao) MissionLidScore(c context.Context, sid, lid int64) (score int64, err error) {
var (
conn = d.redis.Get(c)
key = likeMissionScoreStrKey(sid, lid)
)
defer conn.Close()
if score, err = redis.Int64(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
} else {
err = errors.Wrapf(err, "conn.Do(GET) %s", key)
}
}
return
}
// MissionLidRank .
func (d *Dao) MissionLidRank(c context.Context, sid, lid int64) (rank int64, err error) {
var (
conn = d.redis.Get(c)
key = likeActMissionScoreKey(sid)
)
defer conn.Close()
if rank, err = redis.Int64(conn.Do("ZREVRANK", key, lid)); err != nil {
if err == redis.ErrNil {
err = nil
rank = -1
} else {
err = errors.Wrapf(err, "conn.Do(GET) %s", key)
}
}
return
}
// MissionScoreList score list .
func (d *Dao) MissionScoreList(c context.Context, sid int64, start, end int) (data []int64, err error) {
var (
key = likeActMissionScoreKey(sid)
conn = d.redis.Get(c)
)
defer conn.Close()
vs, err := redis.Values(conn.Do("ZREVRANGE", key, start, end, "WITHSCORES"))
if err != nil {
PromError("redis:获取MissionScoreList", "conn.Do(ZREVRANGE,%s,%d,%d) error(%v)", key, start, end, err)
return
}
data = make([]int64, 0, len(vs))
for len(vs) > 0 {
var (
lid int64
score int64
)
if vs, err = redis.Scan(vs, &lid, &score); err != nil {
PromError("redis:获取获取MissionScoreList", "redis.Scan(%v) error(%v)", vs, err)
return
}
if lid != 0 {
data = append(data, lid)
}
}
return
}
// AddActMission .
func (d *Dao) AddActMission(c context.Context, act *l.ActMissionGroup) (actID int64, err error) {
var res sql.Result
if res, err = d.db.Exec(c, _addLikeActMissionSQL, act.Sid, act.Mid, act.Lid, act.Action, act.IPv6); err != nil {
err = errors.Wrapf(err, "d.db.Exec(%s)", _addLikeActMissionSQL)
return
}
return res.LastInsertId()
}
// RawActMissionFriends .
func (d *Dao) RawActMissionFriends(c context.Context, sid, lid int64) (res *l.ActMissionGroups, err error) {
rows, err := d.db.Query(c, _likeActMissionFriendsSQL, sid, lid)
if err != nil {
err = errors.Wrapf(err, " d.db.Query(%s)", _likeActMissionFriendsSQL)
return
}
list := make([]*l.ActMissionGroup, 0, 100)
for rows.Next() {
n := &l.ActMissionGroup{}
if err = rows.Scan(&n.ID, &n.Sid, &n.Lid, &n.Mid, &n.Action); err != nil {
err = errors.Wrapf(err, " d.db.rows.Scan(%s)", _likeActMissionFriendsSQL)
return
}
list = append(list, n)
}
res = &l.ActMissionGroups{ActMissionGroups: list}
if err = rows.Err(); err != nil {
err = errors.Wrap(err, "rows.Err()")
}
return
}

View File

@@ -0,0 +1,249 @@
package like
import (
"context"
"fmt"
"testing"
l "go-common/app/interface/main/activity/model/like"
"github.com/smartystreets/goconvey/convey"
)
func TestLikemissionLikeLimitKey(t *testing.T) {
convey.Convey("missionLikeLimitKey", t, func(ctx convey.C) {
var (
sid = int64(10256)
mid = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := missionLikeLimitKey(sid, mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikelikeActMissionScoreKey(t *testing.T) {
convey.Convey("likeActMissionScoreKey", t, func(ctx convey.C) {
var (
sid = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := likeActMissionScoreKey(sid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikelikeMissionScoreStrKey(t *testing.T) {
convey.Convey("likeMissionScoreStrKey", t, func(ctx convey.C) {
var (
sid = int64(10256)
lid = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := likeMissionScoreStrKey(sid, lid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikescoreMaxTime(t *testing.T) {
convey.Convey("scoreMaxTime", t, func(ctx convey.C) {
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := scoreMaxTime()
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikescoreMaxNum(t *testing.T) {
convey.Convey("scoreMaxNum", t, func(ctx convey.C) {
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := scoreMaxNum()
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikebuildRankScore(t *testing.T) {
convey.Convey("buildRankScore", t, func(ctx convey.C) {
var (
num = int64(3)
ctime = int64(15487588)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := buildRankScore(num, ctime)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeRawActMission(t *testing.T) {
convey.Convey("RawActMission", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
lid = int64(123)
mid = int64(123)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.RawActMission(c, sid, lid, mid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", res)
})
})
})
}
func TestLikeMissionLikeLimit(t *testing.T) {
convey.Convey("MissionLikeLimit", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
mid = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.MissionLikeLimit(c, sid, mid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", res)
})
})
})
}
func TestLikeInrcMissionLikeLimit(t *testing.T) {
convey.Convey("InrcMissionLikeLimit", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
mid = int64(77)
val = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.InrcMissionLikeLimit(c, sid, mid, val)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", res)
})
})
})
}
func TestLikeSetMissionTop(t *testing.T) {
convey.Convey("SetMissionTop", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
lid = int64(123)
score = int64(1)
ctime = int64(158748596)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
count, err := d.SetMissionTop(c, sid, lid, score, ctime)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", count)
})
})
})
}
func TestLikeMissionLidScore(t *testing.T) {
convey.Convey("MissionLidScore", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
lid = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
score, err := d.MissionLidScore(c, sid, lid)
ctx.Convey("Then err should be nil.score should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(score, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeMissionLidRank(t *testing.T) {
convey.Convey("MissionLidRank", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
lid = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
rank, err := d.MissionLidRank(c, sid, lid)
ctx.Convey("Then err should be nil.rank should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rank, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeMissionScoreList(t *testing.T) {
convey.Convey("MissionScoreList", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
start = int(1)
end = int(2)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
data, err := d.MissionScoreList(c, sid, start, end)
ctx.Convey("Then err should be nil.data should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(data, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeAddActMission(t *testing.T) {
convey.Convey("AddActMission", t, func(ctx convey.C) {
var (
c = context.Background()
act = &l.ActMissionGroup{Sid: 10256, Lid: 1235, Mid: 77, IPv6: make([]byte, 0)}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
actID, err := d.AddActMission(c, act)
ctx.Convey("Then err should be nil.actID should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(actID, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeRawActMissionFriends(t *testing.T) {
convey.Convey("RawActMissionFriends", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
lid = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.RawActMissionFriends(c, sid, lid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,54 @@
package like
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestLikekeyRedDot(t *testing.T) {
convey.Convey("keyRedDot", t, func(ctx convey.C) {
var (
mid = int64(55)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyRedDot(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeCacheRedDotTs(t *testing.T) {
convey.Convey("CacheRedDotTs", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
ts, err := d.CacheRedDotTs(c, mid)
ctx.Convey("Then err should be nil.ts should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(ts, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeAddCacheRedDotTs(t *testing.T) {
convey.Convey("AddCacheRedDotTs", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(77)
ts = int64(14585874)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddCacheRedDotTs(c, mid, ts)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,421 @@
package like
import (
"context"
"database/sql"
"fmt"
"strconv"
"time"
l "go-common/app/interface/main/activity/model/like"
"go-common/library/cache/memcache"
"go-common/library/cache/redis"
xsql "go-common/library/database/sql"
"go-common/library/log"
"go-common/library/stat/prom"
"go-common/library/xstr"
"github.com/pkg/errors"
)
// like_action sql and like state
const (
_likeActInfosSQL = "select id,lid from like_action where lid in (%s) and mid = ?"
_likeActAddSQL = "INSERT INTO like_action(lid,mid,action,sid,ipv6,ctime,mtime) VALUES(?,?,?,?,?,?,?)"
_likeActSumSQL = "select sum(action) likes, lid from like_action where sid = ? and lid in (%s) group by lid ORDER BY likes desc"
_storyActSumSQL = "select sum(action) likes from like_action where sid = ? and mid = ? and ctime >= ? and ctime <= ?"
_storyEachActSumSQL = "select sum(action) likes from like_action where sid = ? and mid = ? and lid = ? and ctime >= ? and ctime <= ?"
HasLike = 1
NoLike = -1
//Total number of activities set the old is bilibili-activity:like:%d
_likeActScoreKeyFmt = "go:bl-a:l:%d"
//Total number of comments for different types of manuscripts
_likeActScoreTyoeKeyFmt = "go:bl:a:l:%d:%d"
//liked key the old is bilibili-activity:like:%d:%d:%d
_likeActKeyFmt = "go:bl-act:l:%d:%d:%d"
//Total number of like the old is likes:oid:%d
_likeLidKeyFmt = "go:ls:oid:%d"
//Total number of activities like the old is sb:likes:count:%d
_likeCountKeyFmt = "go:sb:ls:count:%d"
)
// likeActScoreKey .
func likeActScoreKey(sid int64) string {
return fmt.Sprintf(_likeActScoreKeyFmt, sid)
}
// likeActScoreTypeKey .
func likeActScoreTypeKey(sid int64, ltype int) string {
return fmt.Sprintf(_likeActScoreTyoeKeyFmt, ltype, sid)
}
func likeActKey(sid, lid, mid int64) string {
return fmt.Sprintf(_likeActKeyFmt, sid, lid, mid)
}
// likeLidKey .
func likeLidKey(oid int64) string {
return fmt.Sprintf(_likeLidKeyFmt, oid)
}
// likeCountKey .
func likeCountKey(sid int64) string {
return fmt.Sprintf(_likeCountKeyFmt, sid)
}
// LikeActInfos get likesaction logs.
func (dao *Dao) LikeActInfos(c context.Context, lids []int64, mid int64) (likeActs map[int64]*l.Action, err error) {
var rows *xsql.Rows
if rows, err = dao.db.Query(c, fmt.Sprintf(_likeActInfosSQL, xstr.JoinInts(lids)), mid); err != nil {
if err == xsql.ErrNoRows {
err = nil
} else {
err = errors.Wrapf(err, "LikeActInfos:Query(%s)", _likeActInfosSQL)
return
}
}
defer rows.Close()
likeActs = make(map[int64]*l.Action, len(lids))
for rows.Next() {
a := &l.Action{}
if err = rows.Scan(&a.ID, &a.Lid); err != nil {
err = errors.Wrap(err, "LikeActInfos:scan()")
return
}
likeActs[a.Lid] = a
}
if err = rows.Err(); err != nil {
err = errors.Wrap(err, "LikeActInfos:rows.Err()")
}
return
}
// LikeActSums get like_action likes sum data .
func (dao *Dao) LikeActSums(c context.Context, sid int64, lids []int64) (res []*l.LidLikeSum, err error) {
var rows *xsql.Rows
if rows, err = dao.db.Query(c, fmt.Sprintf(_likeActSumSQL, xstr.JoinInts(lids)), sid); err != nil {
if err == xsql.ErrNoRows {
err = nil
} else {
err = errors.Wrapf(err, "LikeActSums:Query(%s)", _likeActSumSQL)
return
}
}
defer rows.Close()
res = make([]*l.LidLikeSum, 0, len(lids))
for rows.Next() {
a := &l.LidLikeSum{}
if err = rows.Scan(&a.Likes, &a.Lid); err != nil {
err = errors.Wrapf(err, "LikeActSums:Scan(%s)", _likeActSumSQL)
return
}
res = append(res, a)
}
if err = rows.Err(); err != nil {
err = errors.Wrapf(err, "LikeActSums:rows.Err(%s)", _likeActSumSQL)
}
return
}
// StoryLikeActSum .
func (dao *Dao) StoryLikeActSum(c context.Context, sid, mid int64, stime, etime string) (res int64, err error) {
var tt sql.NullInt64
row := dao.db.QueryRow(c, _storyActSumSQL, sid, mid, stime, etime)
if err = row.Scan(&tt); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
err = errors.Wrap(err, "row.Scan()")
}
}
res = tt.Int64
return
}
// StoryEachLikeAct .
func (dao *Dao) StoryEachLikeAct(c context.Context, sid, mid, lid int64, stime, etime string) (res int64, err error) {
var tt sql.NullInt64
row := dao.db.QueryRow(c, _storyEachActSumSQL, sid, mid, lid, stime, etime)
if err = row.Scan(&tt); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
err = errors.Wrap(err, "row.Scan()")
}
}
res = tt.Int64
return
}
// SetRedisCache .
func (dao *Dao) SetRedisCache(c context.Context, sid, lid, score int64, likeType int) (err error) {
var (
conn = dao.redis.Get(c)
key = likeActScoreKey(sid)
lidKey = likeLidKey(lid)
lidCountKey = likeCountKey(sid)
max = 3
)
defer conn.Close()
if err = conn.Send("ZINCRBY", key, score, lid); err != nil {
err = errors.Wrap(err, "conn.Send(ZINCRBY) likeActScoreKey")
return
}
if err = conn.Send("INCRBY", lidKey, score); err != nil {
err = errors.Wrap(err, "conn.Send(INCR) likeLidKey")
return
}
if likeType != 0 {
max++
typeKey := likeActScoreTypeKey(sid, likeType)
if err = conn.Send("ZINCRBY", typeKey, score, lid); err != nil {
err = errors.Wrap(err, "conn.Send(ZINCRBY) likeActScoreTypeKey")
return
}
}
if err = conn.Send("INCRBY", lidCountKey, score); err != nil {
err = errors.Wrap(err, "conn.Send(INCR) likeLidKey")
return
}
if err = conn.Flush(); err != nil {
err = errors.Wrap(err, " conn.Set()")
return
}
for i := 0; i < max; i++ {
if _, err = conn.Receive(); err != nil {
err = errors.Wrap(err, fmt.Sprintf("conn.Receive()%d", i+1))
return
}
}
return
}
// RedisCache get cache order by like .
func (dao *Dao) RedisCache(c context.Context, sid int64, start, end int) (res []*l.LidLikeRes, err error) {
var (
conn = dao.redis.Get(c)
key = likeActScoreKey(sid)
)
defer conn.Close()
values, err := redis.Values(conn.Do("ZREVRANGE", key, start, end, "WITHSCORES"))
if err != nil {
err = errors.Wrap(err, "conn.Do(ZREVRANGE)")
return
}
if len(values) == 0 {
return
}
res = make([]*l.LidLikeRes, 0, len(values))
for len(values) > 0 {
t := &l.LidLikeRes{}
if values, err = redis.Scan(values, &t.Lid, &t.Score); err != nil {
err = errors.Wrap(err, "redis.Scan")
return
}
res = append(res, t)
}
return
}
// LikeActZscore .
func (dao *Dao) LikeActZscore(c context.Context, sid, lid int64) (res int64, err error) {
var (
conn = dao.redis.Get(c)
key = likeActScoreKey(sid)
)
defer conn.Close()
if res, err = redis.Int64(conn.Do("ZSCORE", key, lid)); err != nil {
if err == redis.ErrNil {
err = nil
} else {
err = errors.Wrap(err, "conn.Do(ZSCORE)")
}
}
return
}
// SetInitializeLikeCache initialize like_action like data .
func (dao *Dao) SetInitializeLikeCache(c context.Context, sid int64, lidLikeAct map[int64]int64, typeLike map[int64]int) (err error) {
var (
conn = dao.redis.Get(c)
max = 0
key = likeActScoreKey(sid)
args = redis.Args{}.Add(key)
)
defer conn.Close()
for k, val := range lidLikeAct {
args = args.Add(val).Add(k)
if typeLike[k] != 0 {
keyType := likeActScoreTypeKey(sid, typeLike[k])
argsType := redis.Args{}.Add(keyType).Add(val).Add(k)
if err = conn.Send("ZADD", argsType...); err != nil {
log.Error("SetInitializeLikeCache:conn.Send(zadd) args(%v) error(%v)", argsType, err)
return
}
max++
}
}
if err = conn.Send("ZADD", args...); err != nil {
log.Error("SetInitializeLikeCache:conn.Send(zadd) args(%v) error(%v)", args, err)
return
}
max++
if err = conn.Flush(); err != nil {
err = errors.Wrap(err, "SetInitializeLikeCache:conn.Set()")
return
}
for i := 0; i < max; i++ {
if _, err = conn.Receive(); err != nil {
err = errors.Wrapf(err, "SetInitializeLikeCache:conn.Receive()%d", i+1)
}
}
return
}
// LikeActAdd add like_action .
func (dao *Dao) LikeActAdd(c context.Context, likeAct *l.Action) (id int64, err error) {
var res sql.Result
if res, err = dao.db.Exec(c, _likeActAddSQL, likeAct.Lid, likeAct.Mid, likeAct.Action, likeAct.Sid, likeAct.IPv6, time.Now(), time.Now()); err != nil {
err = errors.Wrapf(err, "d.db.Exec(%s)", _likeActAddSQL)
return
}
return res.LastInsertId()
}
// LikeActLidCounts get lid score.
func (dao *Dao) LikeActLidCounts(c context.Context, lids []int64) (res map[int64]int64, err error) {
var (
conn = dao.redis.Get(c)
args = redis.Args{}
ss []int64
)
defer conn.Close()
for _, lid := range lids {
args = args.Add(likeLidKey(lid))
}
if ss, err = redis.Int64s(conn.Do("MGET", args...)); err != nil {
if err == redis.ErrNil {
err = nil
} else {
err = errors.Wrapf(err, "redis.Ints(conn.Do(HMGET,%v)", args)
}
return
}
res = make(map[int64]int64, len(lids))
for key, val := range ss {
res[lids[key]] = val
}
return
}
// LikeActs get data from cache if miss will call source method, then add to cache.
func (dao *Dao) LikeActs(c context.Context, sid, mid int64, lids []int64) (res map[int64]int, err error) {
var (
miss []int64
likeActInfos map[int64]*l.Action
missVal map[int64]int
)
if len(lids) == 0 {
return
}
addCache := true
res, err = dao.CacheLikeActs(c, sid, mid, lids)
if err != nil {
addCache = false
res = nil
err = nil
}
for _, key := range lids {
if (res == nil) || (res[key] == 0) {
miss = append(miss, key)
}
}
prom.CacheHit.Add("LikeActs", int64(len(lids)-len(miss)))
if len(miss) == 0 {
return
}
if likeActInfos, err = dao.LikeActInfos(c, miss, mid); err != nil {
err = errors.Wrapf(err, "dao.LikeActInfos(%v) error(%v)", miss, err)
return
}
if res == nil {
res = make(map[int64]int)
}
missVal = make(map[int64]int, len(miss))
for _, mcLid := range miss {
if _, ok := likeActInfos[mcLid]; ok {
res[mcLid] = HasLike
} else {
res[mcLid] = NoLike
}
missVal[mcLid] = res[mcLid]
}
if !addCache {
return
}
dao.AddCacheLikeActs(c, sid, mid, missVal)
return
}
// CacheLikeActs res value val -1:no like 1:has like 0:no value.
func (dao *Dao) CacheLikeActs(c context.Context, sid, mid int64, lids []int64) (res map[int64]int, err error) {
l := len(lids)
if l == 0 {
return
}
keysMap := make(map[string]int64, l)
keys := make([]string, 0, l)
for _, id := range lids {
key := likeActKey(sid, id, mid)
keysMap[key] = id
keys = append(keys, key)
}
conn := dao.mc.Get(c)
defer conn.Close()
replies, err := conn.GetMulti(keys)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheLikeActs")
log.Errorv(c, log.KV("CacheLikeActs", fmt.Sprintf("%+v", err)), log.KV("keys", keys))
return
}
for key, reply := range replies {
var v string
err = conn.Scan(reply, &v)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheLikeActs")
log.Errorv(c, log.KV("CacheLikeActs", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
r, err := strconv.ParseInt(v, 10, 64)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheLikeActs")
log.Errorv(c, log.KV("CacheLikeActs", fmt.Sprintf("%+v", err)), log.KV("key", key))
return res, err
}
if res == nil {
res = make(map[int64]int, len(keys))
}
res[keysMap[key]] = int(r)
}
return
}
// AddCacheLikeActs Set data to mc
func (dao *Dao) AddCacheLikeActs(c context.Context, sid, mid int64, values map[int64]int) (err error) {
if len(values) == 0 {
return
}
conn := dao.mc.Get(c)
defer conn.Close()
for id, val := range values {
key := likeActKey(sid, id, mid)
bs := []byte(strconv.FormatInt(int64(val), 10))
item := &memcache.Item{Key: key, Value: bs, Expiration: dao.mcPerpetualExpire, Flags: memcache.FlagRAW}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheLikeActs")
log.Errorv(c, log.KV("AddCacheLikeActs", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
}
return
}

View File

@@ -0,0 +1,312 @@
package like
import (
"context"
l "go-common/app/interface/main/activity/model/like"
"testing"
"fmt"
"github.com/smartystreets/goconvey/convey"
)
func TestLikelikeActScoreKey(t *testing.T) {
convey.Convey("likeActScoreKey", t, func(ctx convey.C) {
var (
sid = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := likeActScoreKey(sid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikelikeActScoreTypeKey(t *testing.T) {
convey.Convey("likeActScoreTypeKey", t, func(ctx convey.C) {
var (
sid = int64(10256)
ltype = int(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := likeActScoreTypeKey(sid, ltype)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikelikeActKey(t *testing.T) {
convey.Convey("likeActKey", t, func(ctx convey.C) {
var (
sid = int64(10256)
lid = int64(77)
mid = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := likeActKey(sid, lid, mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikelikeLidKey(t *testing.T) {
convey.Convey("likeLidKey", t, func(ctx convey.C) {
var (
oid = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := likeLidKey(oid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikelikeCountKey(t *testing.T) {
convey.Convey("likeCountKey", t, func(ctx convey.C) {
var (
sid = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := likeCountKey(sid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeLikeActInfos(t *testing.T) {
convey.Convey("LikeActInfos", t, func(ctx convey.C) {
var (
c = context.Background()
lids = []int64{1, 2}
mid = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
likeActs, err := d.LikeActInfos(c, lids, mid)
ctx.Convey("Then err should be nil.likeActs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(likeActs, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeLikeActSums(t *testing.T) {
convey.Convey("LikeActSums", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(1056)
lids = []int64{1, 2}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.LikeActSums(c, sid, lids)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeStoryLikeActSum(t *testing.T) {
convey.Convey("StoryLikeActSum", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
mid = int64(77)
stime = "2018-10-16 00:00:00"
etime = "2018-10-16 23:59:59"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.StoryLikeActSum(c, sid, mid, stime, etime)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeStoryEachLikeAct(t *testing.T) {
convey.Convey("StoryEachLikeAct", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10296)
mid = int64(216761)
lid = int64(13538)
stime = "2018-10-17 00:00:00"
etime = "2018-10-17 23:59:59"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.StoryEachLikeAct(c, sid, mid, lid, stime, etime)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%d", res)
})
})
})
}
func TestLikeSetRedisCache(t *testing.T) {
convey.Convey("SetRedisCache", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10296)
lid = int64(13538)
score = int64(10)
likeType = int(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetRedisCache(c, sid, lid, score, likeType)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeRedisCache(t *testing.T) {
convey.Convey("RedisCache", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10296)
start = int(0)
end = int(100)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.RedisCache(c, sid, start, end)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", res)
})
})
})
}
func TestLikeLikeActZscore(t *testing.T) {
convey.Convey("LikeActZscore", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10296)
lid = int64(13528)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.LikeActZscore(c, sid, lid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%d", res)
})
})
})
}
func TestLikeSetInitializeLikeCache(t *testing.T) {
convey.Convey("SetInitializeLikeCache", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
lidLikeAct = map[int64]int64{77: 1, 88: 2}
typeLike = map[int64]int{77: 1, 88: 2}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetInitializeLikeCache(c, sid, lidLikeAct, typeLike)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeLikeActAdd(t *testing.T) {
convey.Convey("LikeActAdd", t, func(ctx convey.C) {
var (
c = context.Background()
likeAct = &l.Action{Sid: 10256, Lid: 77, Action: 1, IPv6: make([]byte, 0)}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
id, err := d.LikeActAdd(c, likeAct)
ctx.Convey("Then err should be nil.id should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(id, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeLikeActLidCounts(t *testing.T) {
convey.Convey("LikeActLidCounts", t, func(ctx convey.C) {
var (
c = context.Background()
lids = []int64{2354, 2355}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.LikeActLidCounts(c, lids)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", res)
})
})
})
}
func TestLikeLikeActs(t *testing.T) {
convey.Convey("LikeActs", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
mid = int64(77)
lids = []int64{1, 2}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.LikeActs(c, sid, mid, lids)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeCacheLikeActs(t *testing.T) {
convey.Convey("CacheLikeActs", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(1256)
mid = int64(77)
lids = []int64{1, 2}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.CacheLikeActs(c, sid, mid, lids)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", res)
})
})
})
}
func TestLikeAddCacheLikeActs(t *testing.T) {
convey.Convey("AddCacheLikeActs", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
mid = int64(77)
values = map[int64]int{77: 1}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddCacheLikeActs(c, sid, mid, values)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,187 @@
package like
import (
"context"
"fmt"
likemdl "go-common/app/interface/main/activity/model/like"
)
// likeKey likes table line cache
func likeKey(id int64) string {
return fmt.Sprintf("go_l_id_%d", id)
}
// actSubjectKey act_subject table line cache .
func actSubjectKey(id int64) string {
return fmt.Sprintf("go_s_id_%d", id)
}
// actSubjectMaxIDKey act_subject table max id cache
func actSubjectMaxIDKey() string {
return "go_sub_id_max"
}
// likeMaxIDKey likes table max id cache
func likeMaxIDKey() string {
return "go_like_id_max"
}
// likeMissionBuffKey .
func likeMissionBuffKey(sid, mid int64) string {
return fmt.Sprintf("go_l_m_a_%d_%d", sid, mid)
}
// likeMissionGroupIDkey .
func likeMissionGroupIDkey(lid int64) string {
return fmt.Sprintf("go_l_m_g_id_%d", lid)
}
// likeActMissionKey flag has buff or not.
func likeActMissionKey(sid, lid, mid int64) string {
return fmt.Sprintf("go:b-a:m:l:%d:%d:%d", sid, lid, mid)
}
// actAchieveKey .
func actAchieveKey(sid int64) string {
return fmt.Sprintf("go:a:achs:%d", sid)
}
// actMissionFriendsKey .
func actMissionFriendsKey(sid, lid int64) string {
return fmt.Sprintf("go:a:m:frd:%d:%d", sid, lid)
}
// actUserAchieveKey .
func actUserAchieveKey(id int64) string {
return fmt.Sprintf("go:a:u:m:%d", id)
}
// actUserAchieveAwardKey .
func actUserAchieveAwardKey(id int64) string {
return fmt.Sprintf("go:a:u:a:%d", id)
}
func subjectStatKey(sid int64) string {
return fmt.Sprintf("ob_s_%d", sid)
}
func viewRankKey(sid int64) string {
return fmt.Sprintf("v_r_%d", sid)
}
func likeContentKey(lid int64) string {
return fmt.Sprintf("go_l_ct_%d", lid)
}
func sourceItemKey(sid int64) string {
return fmt.Sprintf("so_i_%d", sid)
}
func subjectProtocolKey(sid int64) string {
return fmt.Sprintf("go_s_pt_%d", sid)
}
//go:generate $GOPATH/src/go-common/app/tool/cache/gen
type _cache interface {
// cache: -sync=true
Like(c context.Context, id int64) (*likemdl.Item, error)
// cache: -sync=true
Likes(c context.Context, ids []int64) (map[int64]*likemdl.Item, error)
// cache: -sync=true
ActSubject(c context.Context, id int64) (*likemdl.SubjectItem, error)
//cache: -sync=true -nullcache=-1 -check_null_code=$==-1
LikeMissionBuff(ctx context.Context, sid int64, mid int64) (res int64, err error)
//cache: -sync=true
MissionGroupItems(ctx context.Context, lids []int64) (map[int64]*likemdl.MissionGroup, error)
//cache: -sync=true -nullcache=-1 -check_null_code=$!=nil&&$==-1
ActMission(ctx context.Context, sid int64, lid int64, mid int64) (res int64, err error)
//cache:-sync=true
ActLikeAchieves(ctx context.Context, sid int64) (res *likemdl.Achievements, err error)
//cache:-sync=true
ActMissionFriends(ctx context.Context, sid int64, lid int64) (res *likemdl.ActMissionGroups, err error)
//cache:-sync=true
ActUserAchieve(ctx context.Context, id int64) (res *likemdl.ActLikeUserAchievement, err error)
// cache
MatchSubjects(c context.Context, ids []int64) (map[int64]*likemdl.Object, error)
// cache:-sync=true
LikeContent(c context.Context, ids []int64) (map[int64]*likemdl.LikeContent, error)
// cache
SourceItemData(c context.Context, sid int64) ([]int64, error)
// cache:-sync=true
ActSubjectProtocol(c context.Context, sid int64) (res *likemdl.ActSubjectProtocol, err error)
}
//go:generate $GOPATH/src/go-common/app/tool/cache/mc
type _mc interface {
// mc: -key=likeKey
CacheLike(c context.Context, id int64) (*likemdl.Item, error)
// mc: -key=likeKey
CacheLikes(c context.Context, id []int64) (map[int64]*likemdl.Item, error)
// mc: -key=likeKey -expire=d.mcPerpetualExpire -encode=json
AddCacheLikes(c context.Context, items map[int64]*likemdl.Item) error
// mc: -key=likeKey -expire=d.mcPerpetualExpire -encode=json
AddCacheLike(c context.Context, key int64, value *likemdl.Item) error
// mc: -key=actSubjectKey
CacheActSubject(c context.Context, id int64) (*likemdl.SubjectItem, error)
// mc: -key=actSubjectKey -expire=d.mcPerpetualExpire -encode=pb
AddCacheActSubject(c context.Context, key int64, value *likemdl.SubjectItem) error
// mc: -key=actSubjectMaxIDKey
CacheActSubjectMaxID(c context.Context) (res int64, err error)
// mc: -key=actSubjectMaxIDKey -expire=d.mcPerpetualExpire -encode=raw
AddCacheActSubjectMaxID(c context.Context, sid int64) error
// mc: -key=likeMaxIDKey
CacheLikeMaxID(c context.Context) (res int64, err error)
// mc: -key=likeMaxIDKey -expire=d.mcPerpetualExpire -encode=raw
AddCacheLikeMaxID(c context.Context, lid int64) error
//mc: -key=likeMissionBuffKey
CacheLikeMissionBuff(c context.Context, sid int64, mid int64) (res int64, err error)
//mc: -key=likeMissionBuffKey
AddCacheLikeMissionBuff(c context.Context, sid int64, val int64, mid int64) error
//mc: -key=likeMissionGroupIDkey
CacheMissionGroupItems(ctx context.Context, lids []int64) (map[int64]*likemdl.MissionGroup, error)
//mc: -key=likeMissionGroupIDkey -expire=d.mcItemExpire -encode=pb
AddCacheMissionGroupItems(ctx context.Context, val map[int64]*likemdl.MissionGroup) error
//mc: -key=likeActMissionKey
CacheActMission(c context.Context, sid int64, lid int64, mid int64) (res int64, err error)
//mc: -key=likeActMissionKey -expire=d.mcPerpetualExpire -encode=raw
AddCacheActMission(c context.Context, sid int64, val int64, lid int64, mid int64) error
//mc: -key=actAchieveKey
CacheActLikeAchieves(c context.Context, sid int64) (res *likemdl.Achievements, err error)
//mc: -key=actAchieveKey -expire=d.mcItemExpire -encode=pb
AddCacheActLikeAchieves(c context.Context, sid int64, res *likemdl.Achievements) error
//mc: -key=actMissionFriendsKey
CacheActMissionFriends(c context.Context, sid int64, lid int64) (res *likemdl.ActMissionGroups, err error)
//mc: -key=actMissionFriendsKey
DelCacheActMissionFriends(c context.Context, sid int64, lid int64) error
//mc: -key=actMissionFriendsKey -expire=d.mcItemExpire -encode=pb
AddCacheActMissionFriends(c context.Context, sid int64, res *likemdl.ActMissionGroups, lid int64) error
//mc: -key=actUserAchieveKey
CacheActUserAchieve(c context.Context, id int64) (res *likemdl.ActLikeUserAchievement, err error)
//mc: -key=actUserAchieveKey -expire=d.mcItemExpire -encode=pb
AddCacheActUserAchieve(c context.Context, id int64, val *likemdl.ActLikeUserAchievement) error
//mc: -key=actUserAchieveAwardKey
CacheActUserAward(c context.Context, id int64) (res int64, err error)
//mc: -key=actUserAchieveAwardKey -expire=d.mcPerpetualExpire -encode=raw
AddCacheActUserAward(c context.Context, id int64, val int64) error
// mc: -key=subjectStatKey
CacheSubjectStat(c context.Context, sid int64) (*likemdl.SubjectStat, error)
// mc: -key=subjectStatKey -expire=d.mcSubStatExpire -encode=json
AddCacheSubjectStat(c context.Context, sid int64, value *likemdl.SubjectStat) error
// mc: -key=viewRankKey
CacheViewRank(c context.Context, sid int64) (string, error)
// mc: -key=viewRankKey -expire=d.mcViewRankExpire -encode=raw
AddCacheViewRank(c context.Context, sid int64, value string) error
// mc: -key=likeContentKey
CacheLikeContent(c context.Context, lids []int64) (res map[int64]*likemdl.LikeContent, err error)
// mc: -key=likeContentKey -expire=d.mcPerpetualExpire -encode=pb
AddCacheLikeContent(c context.Context, val map[int64]*likemdl.LikeContent) error
// mc: -key=sourceItemKey
CacheSourceItemData(c context.Context, sid int64) ([]int64, error)
// mc: -key=sourceItemKey -expire=d.mcSourceItemExpire -encode=json
AddCacheSourceItemData(c context.Context, sid int64, lids []int64) error
// mc: -key=subjectProtocolKey
CacheActSubjectProtocol(c context.Context, sid int64) (res *likemdl.ActSubjectProtocol, err error)
// mc: -key=subjectProtocolKey -expire=d.mcProtocolExpire -encode=pb
AddCacheActSubjectProtocol(c context.Context, sid int64, value *likemdl.ActSubjectProtocol) error
}

View File

@@ -0,0 +1,215 @@
package like
import (
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestLikelikeKey(t *testing.T) {
convey.Convey("likeKey", t, func(ctx convey.C) {
var (
id = int64(7)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := likeKey(id)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeactSubjectKey(t *testing.T) {
convey.Convey("actSubjectKey", t, func(ctx convey.C) {
var (
id = int64(7)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := actSubjectKey(id)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeactSubjectMaxIDKey(t *testing.T) {
convey.Convey("actSubjectMaxIDKey", t, func(ctx convey.C) {
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := actSubjectMaxIDKey()
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikelikeMaxIDKey(t *testing.T) {
convey.Convey("likeMaxIDKey", t, func(ctx convey.C) {
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := likeMaxIDKey()
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikelikeMissionBuffKey(t *testing.T) {
convey.Convey("likeMissionBuffKey", t, func(ctx convey.C) {
var (
sid = int64(10256)
mid = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := likeMissionBuffKey(sid, mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikelikeMissionGroupIDkey(t *testing.T) {
convey.Convey("likeMissionGroupIDkey", t, func(ctx convey.C) {
var (
lid = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := likeMissionGroupIDkey(lid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikelikeActMissionKey(t *testing.T) {
convey.Convey("likeActMissionKey", t, func(ctx convey.C) {
var (
sid = int64(10256)
lid = int64(1)
mid = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := likeActMissionKey(sid, lid, mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeactAchieveKey(t *testing.T) {
convey.Convey("actAchieveKey", t, func(ctx convey.C) {
var (
sid = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := actAchieveKey(sid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeactMissionFriendsKey(t *testing.T) {
convey.Convey("actMissionFriendsKey", t, func(ctx convey.C) {
var (
sid = int64(10256)
lid = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := actMissionFriendsKey(sid, lid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeactUserAchieveKey(t *testing.T) {
convey.Convey("actUserAchieveKey", t, func(ctx convey.C) {
var (
id = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := actUserAchieveKey(id)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeactUserAchieveAwardKey(t *testing.T) {
convey.Convey("actUserAchieveAwardKey", t, func(ctx convey.C) {
var (
id = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := actUserAchieveAwardKey(id)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikesubjectStatKey(t *testing.T) {
convey.Convey("subjectStatKey", t, func(ctx convey.C) {
var (
sid = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := subjectStatKey(sid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeviewRankKey(t *testing.T) {
convey.Convey("viewRankKey", t, func(ctx convey.C) {
var (
sid = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := viewRankKey(sid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikelikeContentKey(t *testing.T) {
convey.Convey("likeContentKey", t, func(ctx convey.C) {
var (
lid = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := likeContentKey(lid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestSubjectProtocolKey(t *testing.T) {
convey.Convey("subjectProtocolKey", t, func(ctx convey.C) {
var (
sid = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := subjectProtocolKey(sid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,38 @@
package like
import (
"context"
"fmt"
l "go-common/app/interface/main/activity/model/like"
"go-common/library/xstr"
"github.com/pkg/errors"
)
const (
_contentSQL = "select id,message,ip,plat,device,ctime,mtime,image,reply,link,ex_name from like_content where id in (%s)"
)
// RawLikeContent .
func (dao *Dao) RawLikeContent(c context.Context, ids []int64) (res map[int64]*l.LikeContent, err error) {
rows, err := dao.db.Query(c, fmt.Sprintf(_contentSQL, xstr.JoinInts(ids)))
if err != nil {
err = errors.Wrap(err, "dao.db.Query()")
return
}
defer rows.Close()
res = make(map[int64]*l.LikeContent, len(ids))
for rows.Next() {
t := &l.LikeContent{}
if err = rows.Scan(&t.ID, &t.Message, &t.IP, &t.Plat, &t.Device, &t.Ctime, &t.Mtime, &t.Image, &t.Reply, &t.Link, &t.ExName); err != nil {
err = errors.Wrapf(err, "rows.Scan()")
return
}
res[t.ID] = t
}
if err = rows.Err(); err != nil {
err = errors.Wrap(err, " rows.Err()")
}
return
}

View File

@@ -0,0 +1,24 @@
package like
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestLikeRawLikeContent(t *testing.T) {
convey.Convey("RawLikeContent", t, func(ctx convey.C) {
var (
c = context.Background()
ids = []int64{1, 2}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.RawLikeContent(c, ids)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,454 @@
// Code generated by $GOPATH/src/go-common/app/tool/cache/gen. DO NOT EDIT.
/*
Package like is a generated cache proxy package.
It is generated from:
type _cache interface {
// cache: -sync=true
Like(c context.Context, id int64) (*likemdl.Item, error)
// cache: -sync=true
Likes(c context.Context, ids []int64) (map[int64]*likemdl.Item, error)
// cache: -sync=true
ActSubject(c context.Context, id int64) (*likemdl.SubjectItem, error)
//cache: -sync=true -nullcache=-1 -check_null_code=$==-1
LikeMissionBuff(ctx context.Context, sid int64, mid int64) (res int64, err error)
//cache: -sync=true
MissionGroupItems(ctx context.Context, lids []int64) (map[int64]*likemdl.MissionGroup, error)
//cache: -sync=true -nullcache=-1 -check_null_code=$!=nil&&$==-1
ActMission(ctx context.Context, sid int64, lid int64, mid int64) (res int64, err error)
//cache:-sync=true
ActLikeAchieves(ctx context.Context, sid int64) (res *likemdl.Achievements, err error)
//cache:-sync=true
ActMissionFriends(ctx context.Context, sid int64, lid int64) (res *likemdl.ActMissionGroups, err error)
//cache:-sync=true
ActUserAchieve(ctx context.Context, id int64) (res *likemdl.ActLikeUserAchievement, err error)
// cache
MatchSubjects(c context.Context, ids []int64) (map[int64]*likemdl.Object, error)
// cache:-sync=true
LikeContent(c context.Context, ids []int64) (map[int64]*likemdl.LikeContent, error)
// cache
SourceItemData(c context.Context, sid int64) ([]int64, error)
// cache:-sync=true
ActSubjectProtocol(c context.Context, sid int64) (res *likemdl.ActSubjectProtocol, err error)
}
*/
package like
import (
"context"
likemdl "go-common/app/interface/main/activity/model/like"
"go-common/library/stat/prom"
)
var _ _cache
// Like get data from cache if miss will call source method, then add to cache.
func (d *Dao) Like(c context.Context, id int64) (res *likemdl.Item, err error) {
addCache := true
res, err = d.CacheLike(c, id)
if err != nil {
addCache = false
err = nil
}
if res != nil {
prom.CacheHit.Incr("Like")
return
}
prom.CacheMiss.Incr("Like")
res, err = d.RawLike(c, id)
if err != nil {
return
}
miss := res
if !addCache {
return
}
d.AddCacheLike(c, id, miss)
return
}
// Likes get data from cache if miss will call source method, then add to cache.
func (d *Dao) Likes(c context.Context, keys []int64) (res map[int64]*likemdl.Item, err error) {
if len(keys) == 0 {
return
}
addCache := true
if res, err = d.CacheLikes(c, keys); err != nil {
addCache = false
res = nil
err = nil
}
var miss []int64
for _, key := range keys {
if (res == nil) || (res[key] == nil) {
miss = append(miss, key)
}
}
prom.CacheHit.Add("Likes", int64(len(keys)-len(miss)))
missLen := len(miss)
if missLen == 0 {
return
}
var missData map[int64]*likemdl.Item
prom.CacheMiss.Add("Likes", int64(len(miss)))
missData, err = d.RawLikes(c, miss)
if res == nil {
res = make(map[int64]*likemdl.Item, len(keys))
}
for k, v := range missData {
res[k] = v
}
if err != nil {
return
}
if !addCache {
return
}
d.AddCacheLikes(c, missData)
return
}
// ActSubject get data from cache if miss will call source method, then add to cache.
func (d *Dao) ActSubject(c context.Context, id int64) (res *likemdl.SubjectItem, err error) {
addCache := true
res, err = d.CacheActSubject(c, id)
if err != nil {
addCache = false
err = nil
}
if res != nil {
prom.CacheHit.Incr("ActSubject")
return
}
prom.CacheMiss.Incr("ActSubject")
res, err = d.RawActSubject(c, id)
if err != nil {
return
}
miss := res
if !addCache {
return
}
d.AddCacheActSubject(c, id, miss)
return
}
// LikeMissionBuff get data from cache if miss will call source method, then add to cache.
func (d *Dao) LikeMissionBuff(c context.Context, id int64, mid int64) (res int64, err error) {
addCache := true
res, err = d.CacheLikeMissionBuff(c, id, mid)
if err != nil {
addCache = false
err = nil
}
defer func() {
if res == -1 {
res = 0
}
}()
if res != 0 {
prom.CacheHit.Incr("LikeMissionBuff")
return
}
prom.CacheMiss.Incr("LikeMissionBuff")
res, err = d.RawLikeMissionBuff(c, id, mid)
if err != nil {
return
}
miss := res
if miss == 0 {
miss = -1
}
if !addCache {
return
}
d.AddCacheLikeMissionBuff(c, id, miss, mid)
return
}
// MissionGroupItems get data from cache if miss will call source method, then add to cache.
func (d *Dao) MissionGroupItems(c context.Context, keys []int64) (res map[int64]*likemdl.MissionGroup, err error) {
if len(keys) == 0 {
return
}
addCache := true
if res, err = d.CacheMissionGroupItems(c, keys); err != nil {
addCache = false
res = nil
err = nil
}
var miss []int64
for _, key := range keys {
if (res == nil) || (res[key] == nil) {
miss = append(miss, key)
}
}
prom.CacheHit.Add("MissionGroupItems", int64(len(keys)-len(miss)))
missLen := len(miss)
if missLen == 0 {
return
}
var missData map[int64]*likemdl.MissionGroup
prom.CacheMiss.Add("MissionGroupItems", int64(len(miss)))
missData, err = d.RawMissionGroupItems(c, miss)
if res == nil {
res = make(map[int64]*likemdl.MissionGroup, len(keys))
}
for k, v := range missData {
res[k] = v
}
if err != nil {
return
}
if !addCache {
return
}
d.AddCacheMissionGroupItems(c, missData)
return
}
// ActMission get data from cache if miss will call source method, then add to cache.
func (d *Dao) ActMission(c context.Context, id int64, lid int64, mid int64) (res int64, err error) {
addCache := true
res, err = d.CacheActMission(c, id, lid, mid)
if err != nil {
addCache = false
err = nil
}
defer func() {
if res == -1 {
res = 0
}
}()
if res != 0 {
prom.CacheHit.Incr("ActMission")
return
}
prom.CacheMiss.Incr("ActMission")
res, err = d.RawActMission(c, id, lid, mid)
if err != nil {
return
}
miss := res
if miss == 0 {
miss = -1
}
if !addCache {
return
}
d.AddCacheActMission(c, id, miss, lid, mid)
return
}
// ActLikeAchieves get data from cache if miss will call source method, then add to cache.
func (d *Dao) ActLikeAchieves(c context.Context, id int64) (res *likemdl.Achievements, err error) {
addCache := true
res, err = d.CacheActLikeAchieves(c, id)
if err != nil {
addCache = false
err = nil
}
if res != nil {
prom.CacheHit.Incr("ActLikeAchieves")
return
}
prom.CacheMiss.Incr("ActLikeAchieves")
res, err = d.RawActLikeAchieves(c, id)
if err != nil {
return
}
miss := res
if !addCache {
return
}
d.AddCacheActLikeAchieves(c, id, miss)
return
}
// ActMissionFriends get data from cache if miss will call source method, then add to cache.
func (d *Dao) ActMissionFriends(c context.Context, id int64, lid int64) (res *likemdl.ActMissionGroups, err error) {
addCache := true
res, err = d.CacheActMissionFriends(c, id, lid)
if err != nil {
addCache = false
err = nil
}
if res != nil {
prom.CacheHit.Incr("ActMissionFriends")
return
}
prom.CacheMiss.Incr("ActMissionFriends")
res, err = d.RawActMissionFriends(c, id, lid)
if err != nil {
return
}
miss := res
if !addCache {
return
}
d.AddCacheActMissionFriends(c, id, miss, lid)
return
}
// ActUserAchieve get data from cache if miss will call source method, then add to cache.
func (d *Dao) ActUserAchieve(c context.Context, id int64) (res *likemdl.ActLikeUserAchievement, err error) {
addCache := true
res, err = d.CacheActUserAchieve(c, id)
if err != nil {
addCache = false
err = nil
}
if res != nil {
prom.CacheHit.Incr("ActUserAchieve")
return
}
prom.CacheMiss.Incr("ActUserAchieve")
res, err = d.RawActUserAchieve(c, id)
if err != nil {
return
}
miss := res
if !addCache {
return
}
d.AddCacheActUserAchieve(c, id, miss)
return
}
// MatchSubjects get data from cache if miss will call source method, then add to cache.
func (d *Dao) MatchSubjects(c context.Context, keys []int64) (res map[int64]*likemdl.Object, err error) {
if len(keys) == 0 {
return
}
addCache := true
if res, err = d.CacheMatchSubjects(c, keys); err != nil {
addCache = false
res = nil
err = nil
}
var miss []int64
for _, key := range keys {
if (res == nil) || (res[key] == nil) {
miss = append(miss, key)
}
}
prom.CacheHit.Add("MatchSubjects", int64(len(keys)-len(miss)))
missLen := len(miss)
if missLen == 0 {
return
}
var missData map[int64]*likemdl.Object
prom.CacheMiss.Add("MatchSubjects", int64(len(miss)))
missData, err = d.RawMatchSubjects(c, miss)
if res == nil {
res = make(map[int64]*likemdl.Object, len(keys))
}
for k, v := range missData {
res[k] = v
}
if err != nil {
return
}
if !addCache {
return
}
d.cache.Do(c, func(c context.Context) {
d.AddCacheMatchSubjects(c, missData)
})
return
}
// LikeContent get data from cache if miss will call source method, then add to cache.
func (d *Dao) LikeContent(c context.Context, keys []int64) (res map[int64]*likemdl.LikeContent, err error) {
if len(keys) == 0 {
return
}
addCache := true
if res, err = d.CacheLikeContent(c, keys); err != nil {
addCache = false
res = nil
err = nil
}
var miss []int64
for _, key := range keys {
if (res == nil) || (res[key] == nil) {
miss = append(miss, key)
}
}
prom.CacheHit.Add("LikeContent", int64(len(keys)-len(miss)))
missLen := len(miss)
if missLen == 0 {
return
}
var missData map[int64]*likemdl.LikeContent
prom.CacheMiss.Add("LikeContent", int64(len(miss)))
missData, err = d.RawLikeContent(c, miss)
if res == nil {
res = make(map[int64]*likemdl.LikeContent, len(keys))
}
for k, v := range missData {
res[k] = v
}
if err != nil {
return
}
if !addCache {
return
}
d.AddCacheLikeContent(c, missData)
return
}
// SourceItemData get data from cache if miss will call source method, then add to cache.
func (d *Dao) SourceItemData(c context.Context, id int64) (res []int64, err error) {
addCache := true
res, err = d.CacheSourceItemData(c, id)
if err != nil {
addCache = false
err = nil
}
if len(res) != 0 {
prom.CacheHit.Incr("SourceItemData")
return
}
prom.CacheMiss.Incr("SourceItemData")
res, err = d.RawSourceItemData(c, id)
if err != nil {
return
}
miss := res
if !addCache {
return
}
d.cache.Do(c, func(c context.Context) {
d.AddCacheSourceItemData(c, id, miss)
})
return
}
// ActSubjectProtocol get data from cache if miss will call source method, then add to cache.
func (d *Dao) ActSubjectProtocol(c context.Context, id int64) (res *likemdl.ActSubjectProtocol, err error) {
addCache := true
res, err = d.CacheActSubjectProtocol(c, id)
if err != nil {
addCache = false
err = nil
}
if res != nil {
prom.CacheHit.Incr("ActSubjectProtocol")
return
}
prom.CacheMiss.Incr("ActSubjectProtocol")
res, err = d.RawActSubjectProtocol(c, id)
if err != nil {
return
}
miss := res
if !addCache {
return
}
d.AddCacheActSubjectProtocol(c, id, miss)
return
}

View File

@@ -0,0 +1,224 @@
package like
import (
"context"
"testing"
"fmt"
"go-common/app/interface/main/activity/model/like"
"github.com/smartystreets/goconvey/convey"
)
func TestLikeLike(t *testing.T) {
convey.Convey("Like", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.Like(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeActSubject(t *testing.T) {
convey.Convey("ActSubject", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.ActSubject(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeLikeMissionBuff(t *testing.T) {
convey.Convey("LikeMissionBuff", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(10256)
mid = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.LikeMissionBuff(c, id, mid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeMissionGroupItems(t *testing.T) {
convey.Convey("MissionGroupItems", t, func(ctx convey.C) {
var (
c = context.Background()
keys = []int64{1, 2}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.MissionGroupItems(c, keys)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeActMission(t *testing.T) {
convey.Convey("ActMission", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(10256)
lid = int64(7)
mid = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.ActMission(c, id, lid, mid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeActLikeAchieves(t *testing.T) {
convey.Convey("ActLikeAchieves", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.ActLikeAchieves(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeActMissionFriends(t *testing.T) {
convey.Convey("ActMissionFriends", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(10256)
lid = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.ActMissionFriends(c, id, lid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeActUserAchieve(t *testing.T) {
convey.Convey("ActUserAchieve", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.ActUserAchieve(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeMatchSubjects(t *testing.T) {
convey.Convey("MatchSubjects", t, func(ctx convey.C) {
var (
c = context.Background()
keys = []int64{10256}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.MatchSubjects(c, keys)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeLikeContent(t *testing.T) {
convey.Convey("LikeContent", t, func(ctx convey.C) {
var (
c = context.Background()
keys = []int64{1, 2}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.LikeContent(c, keys)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestActSubjectProtocol(t *testing.T) {
convey.Convey("LikeContent", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10298)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.ActSubjectProtocol(c, sid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", res)
})
})
})
}
func TestCacheActSubjectProtocol(t *testing.T) {
convey.Convey("LikeContent", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10298)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.CacheActSubjectProtocol(c, sid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", res)
})
})
})
}
func TestAddCacheActSubjectProtocol(t *testing.T) {
convey.Convey("LikeContent", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
protocol = &like.ActSubjectProtocol{ID: 1, Sid: 10256}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddCacheActSubjectProtocol(c, sid, protocol)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,132 @@
package like
import (
"context"
"time"
"go-common/app/interface/main/activity/conf"
"go-common/library/cache/memcache"
"go-common/library/cache/redis"
"go-common/library/database/elastic"
xsql "go-common/library/database/sql"
"go-common/library/log"
httpx "go-common/library/net/http/blademaster"
"go-common/library/stat/prom"
"go-common/library/sync/pipeline/fanout"
)
const (
_lotteryIndex = "/matsuri/api/mission"
_lotteryAddTimes = "/matsuri/api/add/times"
_likeItemURI = "/activity/likes/list/%d"
_sourceItemURI = "/activity/web/view/data/%d"
_tagsURI = "/x/internal/tag/archive/multi/tags"
)
// Dao struct
type Dao struct {
db *xsql.DB
subjectStmt *xsql.Stmt
voteLogStmt *xsql.Stmt
mc *memcache.Pool
mcLikeExpire int32
mcLikeIPExpire int32
mcPerpetualExpire int32
mcItemExpire int32
mcSubStatExpire int32
mcViewRankExpire int32
mcSourceItemExpire int32
mcProtocolExpire int32
redis *redis.Pool
redisExpire int32
matchExpire int32
followExpire int32
hotDotExpire int32
randomExpire int32
lotteryIndexURL string
addLotteryTimesURL string
likeItemURL string
sourceItemURL string
tagURL string
client *httpx.Client
cacheCh chan func()
cache *fanout.Fanout
es *elastic.Elastic
}
// New init
func New(c *conf.Config) (dao *Dao) {
dao = &Dao{
db: xsql.NewMySQL(c.MySQL.Like),
mc: memcache.NewPool(c.Memcache.Like),
mcLikeExpire: int32(time.Duration(c.Memcache.LikeExpire) / time.Second),
mcLikeIPExpire: int32(time.Duration(c.Memcache.LikeIPExpire) / time.Second),
mcPerpetualExpire: int32(time.Duration(c.Memcache.PerpetualExpire) / time.Second),
mcItemExpire: int32(time.Duration(c.Memcache.ItemExpire) / time.Second),
mcSubStatExpire: int32(time.Duration(c.Memcache.SubStatExpire) / time.Second),
mcViewRankExpire: int32(time.Duration(c.Memcache.ViewRankExpire) / time.Second),
mcSourceItemExpire: int32(time.Duration(c.Memcache.SourceItemExpire) / time.Second),
mcProtocolExpire: int32(time.Duration(c.Memcache.ProtocolExpire) / time.Second),
redis: redis.NewPool(c.Redis.Config),
cacheCh: make(chan func(), 1024),
cache: fanout.New("cache", fanout.Worker(1), fanout.Buffer(1024)),
redisExpire: int32(time.Duration(c.Redis.Expire) / time.Second),
matchExpire: int32(time.Duration(c.Redis.MatchExpire) / time.Second),
followExpire: int32(time.Duration(c.Redis.FollowExpire) / time.Second),
hotDotExpire: int32(time.Duration(c.Redis.HotDotExpire) / time.Second),
randomExpire: int32(time.Duration(c.Redis.RandomExpire) / time.Second),
lotteryIndexURL: c.Host.Activity + _lotteryIndex,
addLotteryTimesURL: c.Host.Activity + _lotteryAddTimes,
likeItemURL: c.Host.Activity + _likeItemURI,
sourceItemURL: c.Host.Activity + _sourceItemURI,
tagURL: c.Host.APICo + _tagsURI,
client: httpx.NewClient(c.HTTPClient),
es: elastic.NewElastic(c.Elastic),
}
dao.subjectStmt = dao.db.Prepared(_selSubjectSQL)
dao.voteLogStmt = dao.db.Prepared(_votLogSQL)
go dao.cacheproc()
return
}
// CVoteLog chan Vote Log
func (dao *Dao) CVoteLog(c context.Context, sid int64, aid int64, mid int64, stage int64, vote int64) {
dao.cacheCh <- func() {
dao.VoteLog(c, sid, aid, mid, stage, vote)
}
}
// Close Dao
func (dao *Dao) Close() {
if dao.db != nil {
dao.db.Close()
}
if dao.redis != nil {
dao.redis.Close()
}
if dao.mc != nil {
dao.mc.Close()
}
close(dao.cacheCh)
}
// Ping Dao
func (dao *Dao) Ping(c context.Context) error {
return dao.db.Ping(c)
}
func (dao *Dao) cacheproc() {
for {
f, ok := <-dao.cacheCh
if !ok {
return
}
f()
}
}
// PromError stat and log.
func PromError(name string, format string, args ...interface{}) {
prom.BusinessErrCount.Incr(name)
log.Error(format, args...)
}

View File

@@ -0,0 +1,34 @@
package like
import (
"flag"
"go-common/app/interface/main/activity/conf"
"os"
"testing"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.web-svr.activity")
flag.Set("conf_token", "22edc93e2998bf0cb0bbee661b03d41f")
flag.Set("tree_id", "2873")
flag.Set("conf_version", "docker-1")
flag.Set("deploy_env", "uat")
flag.Set("conf_host", "config.bilibili.co")
flag.Set("conf_path", "/tmp")
flag.Set("region", "sh")
flag.Set("zone", "sh001")
} else {
flag.Set("conf", "../../cmd/activity-test.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
os.Exit(m.Run())
}

View File

@@ -0,0 +1,22 @@
package like
import (
"context"
"fmt"
"github.com/pkg/errors"
)
const (
_addLikeExtendSQL = "insert into like_extend (lid,`like`) values %s ON DUPLICATE KEY UPDATE `like` = values(`like`);"
)
// AddExtend .
func (dao *Dao) AddExtend(c context.Context, query string) (res int64, err error) {
rows, err := dao.db.Exec(c, fmt.Sprintf(_addLikeExtendSQL, query))
if err != nil {
err = errors.Wrap(err, " dao.db.Exec()")
return
}
return rows.RowsAffected()
}

View File

@@ -0,0 +1,25 @@
package like
import (
"context"
"fmt"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestAddExtend(t *testing.T) {
convey.Convey("ipRequestKey", t, func(ctx convey.C) {
var (
c = context.Background()
query = "(2355,10)"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.AddExtend(c, query)
ctx.Convey("Then err should be nil.likes should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%d", res)
})
})
})
}

View File

@@ -0,0 +1,985 @@
package like
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"time"
"go-common/app/interface/main/activity/model/like"
"go-common/library/cache/memcache"
"go-common/library/cache/redis"
"go-common/library/database/elastic"
"go-common/library/database/sql"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
xtime "go-common/library/time"
"go-common/library/xstr"
"github.com/pkg/errors"
)
const (
_selLikeSQL = "SELECT id,wid FROM likes where state = 1 AND sid = ? ORDER BY type"
_likeSQL = "SELECT id,sid,type,mid,wid,state,stick_top,ctime,mtime FROM likes WHERE id = ? and state = 1"
_likeMoreLidSQL = "SELECT id,sid,type,mid,wid,state,stick_top,ctime,mtime FROM likes WHERE id > ? order by id asc limit 1000"
_likesBySidSQL = "SELECT id,sid,type,mid,wid,state,stick_top,ctime,mtime FROM likes WHERE id > ? and sid = ? and state = 1 order by id asc limit 1000"
_likesSQL = "SELECT id,sid,type,mid,wid,state,stick_top,ctime,mtime FROM likes WHERE id IN (%s) and state = 1"
_likeListSQL = "SELECT id,wid,ctime FROM likes WHERE state = 1 AND sid = ? ORDER BY id DESC"
_likeMaxIDSQL = "SELECT id FROM likes ORDER BY id DESC limit 1"
_keyLikeTagFmt = "l_t_%d_%d"
_keyLikeTagCntsFmt = "l_t_cs_%d"
_keyLikeRegionFmt = "l_r_%d_%d"
// likeAPI ip frequence key the old is ddos:like:ip:%s
_keyIPRequestFmt = "go:ddos:l:ip:%s"
// the cache set of like order by ctime the old is bilibili-activity:ctime:%d
_keyLikeListCtimeFmt = "go:bl-a:ctime:%d"
_keyLikeListRandomFmt = "go:bl-a:random:%d"
// the cache set of like type order by ctime
_keyLikeListTypeCtimeFmt = "go:b:a:t:%d:%d"
// storyKing LikeAct cache
_keyStoryDilyLikeFmt = "go:s:d:m:%s:%d:%d"
// storyKing each likeAct cahce
_keyStoryEachLikeFmt = "go:s:ea:m:%s:%d:%d:%d"
// es index
_activity = "activity"
// EsOrderLikes archive center likes.
EsOrderLikes = "likes"
// EsOrderCoin archive center coin .
EsOrderCoin = "coin"
// EsOrderReply archive center reply.
EsOrderReply = "reply"
// EsOrderShare archive center share.
EsOrderShare = "share"
// EsOrderClick archive center click
EsOrderClick = "click"
// EsOrderDm archive center dm
EsOrderDm = "dm"
// EsOrderFav archive center fav
EsOrderFav = "fav"
// ActOrderLike activity list like order.
ActOrderLike = "like"
// ActOrderCtime activity list ctime order.
ActOrderCtime = "ctime"
// ActOrderRandom order random .
ActOrderRandom = "random"
)
// ipRequestKey .
func ipRequestKey(ip string) string {
return fmt.Sprintf(_keyIPRequestFmt, ip)
}
func likeListCtimeKey(sid int64) string {
return fmt.Sprintf(_keyLikeListCtimeFmt, sid)
}
func likeListRandomKey(sid int64) string {
return fmt.Sprintf(_keyLikeListRandomFmt, sid)
}
func likeListTypeCtimeKey(types int, sid int64) string {
return fmt.Sprintf(_keyLikeListTypeCtimeFmt, types, sid)
}
func keyLikeTag(sid, tagID int64) string {
return fmt.Sprintf(_keyLikeTagFmt, sid, tagID)
}
func keyLikeTagCounts(sid int64) string {
return fmt.Sprintf(_keyLikeTagCntsFmt, sid)
}
func keyLikeRegion(sid int64, regionID int16) string {
return fmt.Sprintf(_keyLikeRegionFmt, sid, regionID)
}
func keyStoryLikeKey(sid, mid int64, daily string) string {
return fmt.Sprintf(_keyStoryDilyLikeFmt, daily, sid, mid)
}
func keyStoryEachLike(sid, mid, lid int64, daily string) string {
return fmt.Sprintf(_keyStoryEachLikeFmt, daily, sid, mid, lid)
}
// LikeTypeList dao sql.
func (dao *Dao) LikeTypeList(c context.Context, sid int64) (ns []*like.Like, err error) {
rows, err := dao.db.Query(c, _selLikeSQL, sid)
if err != nil {
log.Error("LikeTypeList dao.db.Query error(%v)", err)
return
}
ns = make([]*like.Like, 0)
defer rows.Close()
for rows.Next() {
n := &like.Like{}
if err = rows.Scan(&n.ID, &n.Wid); err != nil {
log.Error("row.Scan error(%v)", err)
return
}
ns = append(ns, n)
}
if err = rows.Err(); err != nil {
log.Error("row.Scan row error(%v)", err)
}
return
}
// LikeList dao sql
func (dao *Dao) LikeList(c context.Context, sid int64) (ns []*like.Item, err error) {
rows, err := dao.db.Query(c, _likeListSQL, sid)
if err != nil {
log.Error("LikeList dao.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
n := new(like.Item)
if err = rows.Scan(&n.ID, &n.Wid, &n.Ctime); err != nil {
log.Error("row.Scan error(%v)", err)
return
}
ns = append(ns, n)
}
if err = rows.Err(); err != nil {
log.Error("row.Scan row error(%v)", err)
}
return
}
// RawLikes get likes by wid.
func (dao *Dao) RawLikes(c context.Context, ids []int64) (data map[int64]*like.Item, err error) {
rows, err := dao.db.Query(c, fmt.Sprintf(_likesSQL, xstr.JoinInts(ids)))
if err != nil {
log.Error("Likes dao.db.Query error(%v)", err)
return
}
defer rows.Close()
data = make(map[int64]*like.Item)
for rows.Next() {
res := &like.Item{}
if err = rows.Scan(&res.ID, &res.Sid, &res.Type, &res.Mid, &res.Wid, &res.State, &res.StickTop, &res.Ctime, &res.Mtime); err != nil {
log.Error("Likes row.Scan error(%v)", err)
return
}
data[res.ID] = res
}
if err = rows.Err(); err != nil {
log.Error("Likes row.Scan row error(%v)", err)
}
return
}
// LikeTagCache get like tag cache.
func (dao *Dao) LikeTagCache(c context.Context, sid, tagID int64, start, end int) (likes []*like.Item, err error) {
var values []interface{}
key := keyLikeTag(sid, tagID)
conn := dao.redis.Get(c)
defer conn.Close()
if values, err = redis.Values(conn.Do("ZREVRANGE", key, start, end)); err != nil {
log.Error("LikeTagCache conn.Do(ZREVRANGE, %s) error(%v)", key, err)
return
} else if len(values) == 0 {
return
}
for len(values) > 0 {
var bs []byte
if values, err = redis.Scan(values, &bs); err != nil {
log.Error("LikeRegionCache redis.Scan(%v) error(%v)", values, err)
return
}
like := new(like.Item)
if err = json.Unmarshal(bs, &like); err != nil {
log.Error("LikeRegionCache conn.Do(ZRANGE, %s) error(%v)", key, err)
continue
}
if like.ID > 0 {
likes = append(likes, like)
}
}
return
}
// LikeTagCnt get like tag cnt.
func (dao *Dao) LikeTagCnt(c context.Context, sid, tagID int64) (count int, err error) {
key := keyLikeTag(sid, tagID)
conn := dao.redis.Get(c)
defer conn.Close()
if count, err = redis.Int(conn.Do("ZCARD", key)); err != nil {
log.Error("LikeRegionCnt conn.Do(ZCARD, %s) error(%v)", key, err)
}
return
}
// SetLikeTagCache set like tag cache no expire.
func (dao *Dao) SetLikeTagCache(c context.Context, sid, tagID int64, likes []*like.Item) (err error) {
var bs []byte
key := keyLikeTag(sid, tagID)
conn := dao.redis.Get(c)
defer conn.Close()
if err = conn.Send("DEL", key); err != nil {
log.Error("SetLikeTagCache conn.Send(DEL, %s) error(%v)", key, err)
return
}
args := redis.Args{}.Add(key)
for _, v := range likes {
if bs, err = json.Marshal(v); err != nil {
log.Error("SetLikeTagCache json.Marshal() error(%v)", err)
return
}
args = args.Add(v.Ctime).Add(bs)
}
if err = conn.Send("ZADD", args...); err != nil {
log.Error("conn.Send(ZADD, %s) error(%v)", key, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}
// LikeRegionCache get like region cache.
func (dao *Dao) LikeRegionCache(c context.Context, sid int64, regionID int16, start, end int) (likes []*like.Item, err error) {
var values []interface{}
key := keyLikeRegion(sid, regionID)
conn := dao.redis.Get(c)
defer conn.Close()
if values, err = redis.Values(conn.Do("ZREVRANGE", key, start, end)); err != nil {
log.Error("LikeRegionCache conn.Do(ZREVRANGE, %s) error(%v)", key, err)
return
} else if len(values) == 0 {
return
}
for len(values) > 0 {
var bs []byte
if values, err = redis.Scan(values, &bs); err != nil {
log.Error("LikeRegionCache redis.Scan(%v) error(%v)", values, err)
return
}
like := new(like.Item)
if err = json.Unmarshal(bs, &like); err != nil {
log.Error("LikeRegionCache conn.Do(ZREVRANGE, %s) error(%v)", key, err)
continue
}
if like.ID > 0 {
likes = append(likes, like)
}
}
return
}
// LikeRegionCnt get like region cnt.
func (dao *Dao) LikeRegionCnt(c context.Context, sid int64, regionID int16) (count int, err error) {
key := keyLikeRegion(sid, regionID)
conn := dao.redis.Get(c)
defer conn.Close()
if count, err = redis.Int(conn.Do("ZCARD", key)); err != nil {
log.Error("LikeRegionCnt conn.Do(ZCARD, %s) error(%v)", key, err)
}
return
}
// SetLikeRegionCache set like region cache.
func (dao *Dao) SetLikeRegionCache(c context.Context, sid int64, regionID int16, likes []*like.Item) (err error) {
var bs []byte
key := keyLikeRegion(sid, regionID)
conn := dao.redis.Get(c)
defer conn.Close()
if err = conn.Send("DEL", key); err != nil {
log.Error("SetLikeTagCache conn.Send(DEL, %s) error(%v)", key, err)
return
}
args := redis.Args{}.Add(key)
for _, v := range likes {
if bs, err = json.Marshal(v); err != nil {
log.Error("SetLikeRegionCache json.Marshal() error(%v)", err)
return
}
args = args.Add(v.Ctime).Add(bs)
}
if err = conn.Send("ZADD", args...); err != nil {
log.Error("conn.Send(ZADD, %s) error(%v)", key, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}
// SetTagLikeCountsCache .
func (dao *Dao) SetTagLikeCountsCache(c context.Context, sid int64, counts map[int64]int32) (err error) {
key := keyLikeTagCounts(sid)
conn := dao.redis.Get(c)
defer conn.Close()
args := redis.Args{}.Add(key)
for tagID, count := range counts {
args = args.Add(tagID).Add(count)
}
if _, err = conn.Do("HMSET", args...); err != nil {
log.Error("SetLikeCountsCache conn.Do(HMSET) key(%s) error(%v)", key, err)
}
return
}
// TagLikeCountsCache get tag like counts cache.
func (dao *Dao) TagLikeCountsCache(c context.Context, sid int64, tagIDs []int64) (counts map[int64]int32, err error) {
if len(tagIDs) == 0 {
return
}
key := keyLikeTagCounts(sid)
conn := dao.redis.Get(c)
defer conn.Close()
args := redis.Args{}.Add(key).AddFlat(tagIDs)
var tmpCounts []int
if tmpCounts, err = redis.Ints(conn.Do("HMGET", args...)); err != nil {
log.Error("redis.Ints(HMGET) key(%s) args(%v) error(%v)", key, args, err)
return
}
if len(tmpCounts) != len(tagIDs) {
return
}
counts = make(map[int64]int32, len(tagIDs))
for i, tagID := range tagIDs {
counts[tagID] = int32(tmpCounts[i])
}
return
}
// RawLike get like by id .
func (dao *Dao) RawLike(c context.Context, id int64) (res *like.Item, err error) {
res = new(like.Item)
row := dao.db.QueryRow(c, _likeSQL, id)
if err = row.Scan(&res.ID, &res.Sid, &res.Type, &res.Mid, &res.Wid, &res.State, &res.StickTop, &res.Ctime, &res.Mtime); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
err = errors.Wrap(err, "LikeByID:QueryRow")
}
}
return
}
// LikeListMoreLid get likes data with like.id greater than lid
func (dao *Dao) LikeListMoreLid(c context.Context, lid int64) (res []*like.Item, err error) {
var rows *sql.Rows
if rows, err = dao.db.Query(c, _likeMoreLidSQL, lid); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
err = errors.Wrap(err, "LikeListMoreLid:dao.db.Query()")
}
return
}
defer rows.Close()
res = make([]*like.Item, 0, 1000)
for rows.Next() {
a := &like.Item{}
if err = rows.Scan(&a.ID, &a.Sid, &a.Type, &a.Mid, &a.Wid, &a.State, &a.StickTop, &a.Ctime, &a.Mtime); err != nil {
err = errors.Wrap(err, "LikeListMoreLid:rows.Scan()")
return
}
res = append(res, a)
}
if err = rows.Err(); err != nil {
err = errors.Wrap(err, "LikeListMoreLid: rows.Err()")
}
return
}
// LikesBySid get sid all likes .
func (dao *Dao) LikesBySid(c context.Context, lid, sid int64) (res []*like.Item, err error) {
var rows *sql.Rows
if rows, err = dao.db.Query(c, _likesBySidSQL, lid, sid); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
err = errors.Wrap(err, "LikesBySid:dao.db.Query()")
}
return
}
defer rows.Close()
res = make([]*like.Item, 0, 1000)
for rows.Next() {
a := &like.Item{}
if err = rows.Scan(&a.ID, &a.Sid, &a.Type, &a.Mid, &a.Wid, &a.State, &a.StickTop, &a.Ctime, &a.Mtime); err != nil {
err = errors.Wrap(err, "LikesBySid:rows.Scan()")
return
}
res = append(res, a)
}
if err = rows.Err(); err != nil {
err = errors.Wrap(err, "LikesBySid:rows.Err()")
}
return
}
// IPReqquestCheck check ip has ben used or not .
func (dao *Dao) IPReqquestCheck(c context.Context, ip string) (val int, err error) {
var (
mcKey = ipRequestKey(ip)
conn = dao.mc.Get(c)
item *memcache.Item
)
defer conn.Close()
if item, err = conn.Get(mcKey); err != nil {
if err == memcache.ErrNotFound {
err = nil
val = 0
} else {
err = errors.Wrap(err, "IPReqquestCheck:conn.Get() error")
}
return
}
if err = conn.Scan(item, &val); err != nil {
err = errors.Wrap(err, "IPReqquestCheck:conn.Scan() ")
}
return
}
// SetIPRequest set ip has been used
func (dao *Dao) SetIPRequest(c context.Context, ip string) (err error) {
var (
conn = dao.mc.Get(c)
item = &memcache.Item{
Key: ipRequestKey(ip),
Expiration: dao.mcLikeIPExpire,
Flags: memcache.FlagRAW,
Value: []byte("1"),
}
)
defer conn.Close()
if err = conn.Set(item); err != nil {
err = errors.Wrap(err, "SetIPRequest:conn.Set()")
}
return
}
// LikeCtime .
func (dao *Dao) LikeCtime(c context.Context, sid int64, start, end int) (res []int64, err error) {
var (
conn = dao.redis.Get(c)
key = likeListCtimeKey(sid)
)
defer conn.Close()
if res, err = redis.Int64s(conn.Do("ZREVRANGE", key, start, end)); err != nil {
if err == redis.ErrNil {
err = nil
} else {
err = errors.Wrap(err, "conn.Do(ZREVRANGE)")
}
}
return
}
// LikeRandom .
func (dao *Dao) LikeRandom(c context.Context, sid int64, start, end int) (res []int64, err error) {
var (
conn = dao.redis.Get(c)
key = likeListRandomKey(sid)
)
defer conn.Close()
if res, err = redis.Int64s(conn.Do("ZREVRANGE", key, start, end)); err != nil {
if err == redis.ErrNil {
err = nil
} else {
err = errors.Wrap(err, "conn.Do(ZREVRANGE)")
}
}
return
}
// LikeRandomCount .
func (dao *Dao) LikeRandomCount(c context.Context, sid int64) (res int64, err error) {
var (
conn = dao.redis.Get(c)
key = likeListRandomKey(sid)
)
defer conn.Close()
if res, err = redis.Int64(conn.Do("ZCARD", key)); err != nil {
log.Error("LikeRandomCount conn.Do(ZCARD, %s) error(%v)", key, err)
}
return
}
// SetLikeRandom .
func (dao *Dao) SetLikeRandom(c context.Context, sid int64, ids []int64) (err error) {
var (
conn = dao.redis.Get(c)
key = likeListRandomKey(sid)
)
defer conn.Close()
if len(ids) == 0 {
return
}
args := redis.Args{}.Add(key)
for k, v := range ids {
args = args.Add(k + 1).Add(v)
}
if err = conn.Send("ZADD", args...); err != nil {
err = errors.Wrap(err, "conn.Send(ZADD)")
return
}
if err = conn.Send("EXPIRE", key, dao.randomExpire); err != nil {
err = errors.Wrap(err, "conn.Send(EXPIRE)")
return
}
if err = conn.Flush(); err != nil {
err = errors.Wrap(err, "conn.Flush()")
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
err = errors.Wrapf(err, "conn.Receive(%d)", i)
return
}
}
return
}
// LikeCount .
func (dao *Dao) LikeCount(c context.Context, sid int64) (res int64, err error) {
var (
conn = dao.redis.Get(c)
key = likeListCtimeKey(sid)
)
defer conn.Close()
if res, err = redis.Int64(conn.Do("ZCARD", key)); err != nil {
log.Error("LikeCount conn.Do(ZCARD, %s) error(%v)", key, err)
}
return
}
// LikeListCtime set like list by ctime.
func (dao *Dao) LikeListCtime(c context.Context, sid int64, items []*like.Item) (err error) {
var (
conn = dao.redis.Get(c)
key = likeListCtimeKey(sid)
max = 0
)
defer conn.Close()
args := redis.Args{}.Add(key)
for _, v := range items {
args = args.Add(v.Ctime).Add(v.ID)
if v.Type != 0 {
typeKey := likeListTypeCtimeKey(v.Type, sid)
typeArgs := redis.Args{}.Add(typeKey).Add(v.Ctime).Add(v.ID)
if err = conn.Send("ZADD", typeArgs...); err != nil {
log.Error("LikeListCtime:conn.Send(%v) error(%v)", v, err)
return
}
max++
}
}
if err = conn.Send("ZADD", args...); err != nil {
log.Error("LikeListCtime:conn.Send(%v) error(%v)", items, err)
return
}
max++
if err = conn.Flush(); err != nil {
log.Error("LikeListCtime:conn.Flush error(%v)", err)
return
}
for i := 0; i < max; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("LikeListCtime:conn.Receive(%d) error(%v)", i, err)
return
}
}
return
}
//DelLikeListCtime delete likeList Ctime cache .
func (dao *Dao) DelLikeListCtime(c context.Context, sid int64, items []*like.Item) (err error) {
var (
conn = dao.redis.Get(c)
key = likeListCtimeKey(sid)
max = 0
)
defer conn.Close()
args := redis.Args{}.Add(key)
for _, v := range items {
args = args.Add(v.ID)
if v.Type != 0 {
typeKey := likeListTypeCtimeKey(v.Type, sid)
if err = conn.Send("ZREM", typeKey, v.ID); err != nil {
log.Error("DelLikeListCtime:conn.Send(%v) error(%v)", v, err)
return
}
max++
}
}
if err = conn.Send("ZREM", args...); err != nil {
log.Error("DelLikeListCtime:conn.Send(%v) error(%v)", args, err)
return
}
max++
if err = conn.Flush(); err != nil {
log.Error("DelLikeListCtime:conn.Flush error(%v)", err)
return
}
for i := 0; i < max; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("DelLikeListCtime:conn.Receive(%d) error(%v)", i, err)
return
}
}
return
}
// LikeMaxID get likes last id .
func (dao *Dao) LikeMaxID(c context.Context) (res *like.Item, err error) {
res = new(like.Item)
rows := dao.db.QueryRow(c, _likeMaxIDSQL)
if err = rows.Scan(&res.ID); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
err = errors.Wrap(err, "LikeMaxID:QueryRow")
}
}
return
}
// GroupItemData like data.
func (dao *Dao) GroupItemData(c context.Context, sid int64, ck string) (data []*like.GroupItem, err error) {
var req *http.Request
if req, err = dao.client.NewRequest(http.MethodGet, fmt.Sprintf(dao.likeItemURL, sid), metadata.String(c, metadata.RemoteIP), url.Values{}); err != nil {
return
}
req.Header.Set("Cookie", ck)
var res struct {
Code int `json:"code"`
Data struct {
List []*like.GroupItem `json:"list"`
} `json:"data"`
}
if err = dao.client.Do(c, req, &res, dao.likeItemURL); err != nil {
err = errors.Wrapf(err, "LikeData dao.client.Do sid(%d)", sid)
return
}
if res.Code != ecode.OK.Code() {
err = errors.Wrapf(ecode.Int(res.Code), "LikeData sid(%d)", sid)
return
}
data = res.Data.List
return
}
// RawSourceItemData get source data.
func (dao *Dao) RawSourceItemData(c context.Context, sid int64) (sids []int64, err error) {
var res struct {
Code int `json:"code"`
Data struct {
List []*struct {
Data struct {
Sid string `json:"sid"`
} `json:"data"`
} `json:"list"`
} `json:"data"`
}
if err = dao.client.RESTfulGet(c, dao.sourceItemURL, metadata.String(c, metadata.RemoteIP), url.Values{}, &res, sid); err != nil {
err = errors.Wrapf(err, "LikeData dao.client.RESTfulGet sid(%d)", sid)
return
}
if res.Code != ecode.OK.Code() {
err = errors.Wrapf(ecode.Int(res.Code), "LikeData sid(%d)", sid)
return
}
for _, v := range res.Data.List {
if sid, e := strconv.ParseInt(v.Data.Sid, 10, 64); e != nil {
continue
} else {
sids = append(sids, sid)
}
}
return
}
// SourceItem get source data json raw message.
func (dao *Dao) SourceItem(c context.Context, sid int64) (source json.RawMessage, err error) {
var res struct {
Code int `json:"code"`
Data json.RawMessage `json:"data"`
}
if err = dao.client.RESTfulGet(c, dao.sourceItemURL, metadata.String(c, metadata.RemoteIP), url.Values{}, &res, sid); err != nil {
err = errors.Wrapf(err, "LikeData dao.client.RESTfulGet sid(%d)", sid)
return
}
if res.Code != ecode.OK.Code() {
err = errors.Wrapf(ecode.Int(res.Code), "LikeData sid(%d)", sid)
return
}
source = res.Data
return
}
// StoryLikeSum .
func (dao *Dao) StoryLikeSum(c context.Context, sid, mid int64) (res int64, err error) {
var (
conn = dao.redis.Get(c)
now = time.Now().Format("2006-01-02")
key = keyStoryLikeKey(sid, mid, now)
)
defer conn.Close()
if res, err = redis.Int64(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
res = -1
} else {
err = errors.Wrap(err, "redis.Do(get)")
}
}
return
}
// IncrStoryLikeSum .
func (dao *Dao) IncrStoryLikeSum(c context.Context, sid, mid int64, score int64) (res int64, err error) {
var (
conn = dao.redis.Get(c)
now = time.Now().Format("2006-01-02")
key = keyStoryLikeKey(sid, mid, now)
)
defer conn.Close()
if res, err = redis.Int64(conn.Do("INCRBY", key, score)); err != nil {
err = errors.Wrap(err, "redis.Do(get)")
}
return
}
// SetLikeSum .
func (dao *Dao) SetLikeSum(c context.Context, sid, mid int64, sum int64) (err error) {
var (
conn = dao.redis.Get(c)
now = time.Now().Format("2006-01-02")
key = keyStoryLikeKey(sid, mid, now)
res bool
)
defer conn.Close()
if res, err = redis.Bool(conn.Do("SETNX", key, sum)); err != nil {
err = errors.Wrap(err, "redis.Bool(SETNX)")
return
}
if res {
conn.Do("EXPIRE", key, 86400)
} else {
err = errors.New("redis.Bool(SETNX) res false")
}
return
}
// StoryEachLikeSum .
func (dao *Dao) StoryEachLikeSum(c context.Context, sid, mid, lid int64) (res int64, err error) {
var (
conn = dao.redis.Get(c)
now = time.Now().Format("2006-01-02")
key = keyStoryEachLike(sid, mid, lid, now)
)
defer conn.Close()
if res, err = redis.Int64(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
res = -1
} else {
err = errors.Wrap(err, "redis.Do(get)")
}
}
return
}
// IncrStoryEachLikeAct .
func (dao *Dao) IncrStoryEachLikeAct(c context.Context, sid, mid, lid int64, score int64) (res int64, err error) {
var (
conn = dao.redis.Get(c)
now = time.Now().Format("2006-01-02")
key = keyStoryEachLike(sid, mid, lid, now)
)
defer conn.Close()
if res, err = redis.Int64(conn.Do("INCRBY", key, score)); err != nil {
err = errors.Wrap(err, "redis.Do(get)")
}
return
}
// SetEachLikeSum .
func (dao *Dao) SetEachLikeSum(c context.Context, sid, mid, lid int64, sum int64) (err error) {
var (
conn = dao.redis.Get(c)
now = time.Now().Format("2006-01-02")
key = keyStoryEachLike(sid, mid, lid, now)
res bool
)
defer conn.Close()
if res, err = redis.Bool(conn.Do("SETNX", key, sum)); err != nil {
err = errors.Wrap(err, "redis.Bool(SETNX)")
return
}
if res {
conn.Do("EXPIRE", key, 86400)
} else {
err = errors.New("redis.Bool(SETNX) res false")
}
return
}
// ListFromES .
func (dao *Dao) ListFromES(c context.Context, sid int64, order string, ps, pn int, seed int64) (res *like.ListInfo, err error) {
actResult := new(struct {
Result []struct {
ID int64 `json:"id"`
Wid int64 `json:"wid"`
Ctime xtime.Time `json:"ctime"`
Sid int64 `json:"sid"`
Type int `json:"type"`
Mid int64 `json:"mid"`
State int `json:"state"`
Mtime xtime.Time `json:"mtime"`
Likes int64 `json:"likes"`
Click int64 `json:"click"`
Coin int64 `json:"coin"`
Share int64 `json:"share"`
Reply int64 `json:"reply"`
Dm int64 `json:"dm"`
Fav int64 `json:"fav"`
} `json:"result"`
Page *like.Page `json:"page"`
})
req := dao.es.NewRequest(_activity).Index(_activity).WhereEq("sid", sid).WhereEq("state", 1).Ps(ps).Pn(pn)
if order != "" {
req.Order(order, elastic.OrderDesc)
}
if seed > 0 {
req.OrderRandomSeed(time.Unix(seed, 0).Format("2006-01-02 15:04:05"))
}
req.Fields("id", "sid", "wid", "mid", "type", "ctime", "mtime", "state", "click", "likes", "coin", "share", "reply", "dm", "fav")
if err = req.Scan(c, &actResult); err != nil {
err = errors.Wrap(err, "req.Scan")
return
}
if len(actResult.Result) == 0 {
return
}
res = &like.ListInfo{Page: actResult.Page, List: make([]*like.List, 0, len(actResult.Result))}
for _, v := range actResult.Result {
a := &like.List{
Likes: v.Likes,
Click: v.Click,
Coin: v.Coin,
Share: v.Share,
Reply: v.Reply,
Dm: v.Dm,
Fav: v.Fav,
Item: &like.Item{
ID: v.ID,
Wid: v.Wid,
Ctime: v.Ctime,
Sid: v.Sid,
Type: v.Type,
Mid: v.Mid,
State: v.State,
Mtime: v.Mtime,
},
}
res.List = append(res.List, a)
}
return
}
// MultiTags .
func (dao *Dao) MultiTags(c context.Context, wids []int64) (tagList map[int64][]string, err error) {
if len(wids) == 0 {
return
}
var res struct {
Code int `json:"code"`
Data map[int64][]*like.Tag `json:"data"`
}
params := url.Values{}
params.Set("aids", xstr.JoinInts(wids))
if err = dao.client.Get(c, dao.tagURL, "", params, &res); err != nil {
log.Error("MultiTags:dao.client.Get(%s) error(%+v)", dao.tagURL, err)
return
}
if res.Code != ecode.OK.Code() {
err = ecode.Int(res.Code)
return
}
tagList = make(map[int64][]string, len(res.Data))
for k, v := range res.Data {
if len(v) == 0 {
continue
}
tagList[k] = make([]string, 0, len(v))
for _, val := range v {
tagList[k] = append(tagList[k], val.Name)
}
}
return
}
// OidInfoFromES .
func (dao *Dao) OidInfoFromES(c context.Context, oids []int64, sType int) (res map[int64]*like.Item, err error) {
actResult := new(struct {
Result []struct {
ID int64 `json:"id"`
Wid int64 `json:"wid"`
Ctime xtime.Time `json:"ctime"`
Sid int64 `json:"sid"`
Type int `json:"type"`
Mid int64 `json:"mid"`
State int `json:"state"`
Mtime xtime.Time `json:"mtime"`
Likes int64 `json:"likes"`
Click int64 `json:"click"`
Coin int64 `json:"coin"`
Share int64 `json:"share"`
Reply int64 `json:"reply"`
Dm int64 `json:"dm"`
Fav int64 `json:"fav"`
} `json:"result"`
Page *like.Page `json:"page"`
})
req := dao.es.NewRequest(_activity).Index(_activity).WhereIn("wid", oids).WhereEq("type", sType)
req.Fields("id", "sid", "wid", "mid", "type", "ctime", "mtime", "state")
if err = req.Scan(c, &actResult); err != nil {
err = errors.Wrap(err, "req.Scan")
return
}
if len(actResult.Result) == 0 {
return
}
res = make(map[int64]*like.Item, len(actResult.Result))
for _, v := range actResult.Result {
res[v.Wid] = &like.Item{
ID: v.ID,
Wid: v.Wid,
Ctime: v.Ctime,
Sid: v.Sid,
Type: v.Type,
Mid: v.Mid,
State: v.State,
Mtime: v.Mtime,
}
}
return
}

View File

@@ -0,0 +1,645 @@
package like
import (
"context"
"encoding/json"
"fmt"
"testing"
"time"
"go-common/app/interface/main/activity/model/like"
"github.com/smartystreets/goconvey/convey"
)
func TestLikeipRequestKey(t *testing.T) {
convey.Convey("ipRequestKey", t, func(ctx convey.C) {
var (
ip = "10.256.8.3"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := ipRequestKey(ip)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikelikeListCtimeKey(t *testing.T) {
convey.Convey("likeListCtimeKey", t, func(ctx convey.C) {
var (
sid = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := likeListCtimeKey(sid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeListRandomKey(t *testing.T) {
convey.Convey("likeListCtimeKey", t, func(ctx convey.C) {
var (
sid = int64(10256)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1 := likeListRandomKey(sid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikelikeListTypeCtimeKey(t *testing.T) {
convey.Convey("likeListTypeCtimeKey", t, func(ctx convey.C) {
var (
types = int(1)
sid = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := likeListTypeCtimeKey(types, sid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikekeyLikeTag(t *testing.T) {
convey.Convey("keyLikeTag", t, func(ctx convey.C) {
var (
sid = int64(10256)
tagID = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyLikeTag(sid, tagID)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikekeyLikeTagCounts(t *testing.T) {
convey.Convey("keyLikeTagCounts", t, func(ctx convey.C) {
var (
sid = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyLikeTagCounts(sid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikekeyLikeRegion(t *testing.T) {
convey.Convey("keyLikeRegion", t, func(ctx convey.C) {
var (
sid = int64(10256)
regionID = int16(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyLikeRegion(sid, regionID)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikekeyStoryLikeKey(t *testing.T) {
convey.Convey("keyStoryLikeKey", t, func(ctx convey.C) {
var (
sid = int64(10256)
mid = int64(1)
daily = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyStoryLikeKey(sid, mid, daily)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikekeyStoryEachLike(t *testing.T) {
convey.Convey("keyStoryEachLike", t, func(ctx convey.C) {
var (
sid = int64(10256)
mid = int64(1)
lid = int64(1)
daily = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyStoryEachLike(sid, mid, lid, daily)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeLikeList(t *testing.T) {
convey.Convey("LikeList", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
ns, err := d.LikeList(c, sid)
ctx.Convey("Then err should be nil.ns should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(ns, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeLikeTagCache(t *testing.T) {
convey.Convey("LikeTagCache", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
tagID = int64(1)
start = int(1)
end = int(2)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
likes, err := d.LikeTagCache(c, sid, tagID, start, end)
ctx.Convey("Then err should be nil.likes should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", likes)
})
})
})
}
func TestLikeLikeTagCnt(t *testing.T) {
convey.Convey("LikeTagCnt", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
tagID = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
count, err := d.LikeTagCnt(c, sid, tagID)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeLikeRegionCache(t *testing.T) {
convey.Convey("LikeRegionCache", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
regionID = int16(1)
start = int(1)
end = int(2)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
likes, err := d.LikeRegionCache(c, sid, regionID, start, end)
ctx.Convey("Then err should be nil.likes should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", likes)
})
})
})
}
func TestLikeLikeRegionCnt(t *testing.T) {
convey.Convey("LikeRegionCnt", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
regionID = int16(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
count, err := d.LikeRegionCnt(c, sid, regionID)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeSetLikeRegionCache(t *testing.T) {
convey.Convey("SetLikeRegionCache", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
regionID = int16(1)
likes = []*like.Item{{Sid: 10256, Wid: 1, Mid: 44}}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetLikeRegionCache(c, sid, regionID, likes)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeSetTagLikeCountsCache(t *testing.T) {
convey.Convey("SetTagLikeCountsCache", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
counts = map[int64]int32{1: 2}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetTagLikeCountsCache(c, sid, counts)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeTagLikeCountsCache(t *testing.T) {
convey.Convey("TagLikeCountsCache", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
tagIDs = []int64{1}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
counts, err := d.TagLikeCountsCache(c, sid, tagIDs)
ctx.Convey("Then err should be nil.counts should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(counts, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeRawLike(t *testing.T) {
convey.Convey("RawLike", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.RawLike(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeLikeListMoreLid(t *testing.T) {
convey.Convey("LikeListMoreLid", t, func(ctx convey.C) {
var (
c = context.Background()
lid = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.LikeListMoreLid(c, lid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeLikesBySid(t *testing.T) {
convey.Convey("LikesBySid", t, func(ctx convey.C) {
var (
c = context.Background()
lid = int64(77)
sid = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.LikesBySid(c, lid, sid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeIPReqquestCheck(t *testing.T) {
convey.Convey("IPReqquestCheck", t, func(ctx convey.C) {
var (
c = context.Background()
ip = "10.248.56.23"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
val, err := d.IPReqquestCheck(c, ip)
ctx.Convey("Then err should be nil.val should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(val, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeSetIPRequest(t *testing.T) {
convey.Convey("SetIPRequest", t, func(ctx convey.C) {
var (
c = context.Background()
ip = "10.248.56.23"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetIPRequest(c, ip)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeLikeListCtime(t *testing.T) {
convey.Convey("LikeListCtime", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
items = []*like.Item{{Sid: 10256, Wid: 55, Mid: 234}}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.LikeListCtime(c, sid, items)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeDelLikeListCtime(t *testing.T) {
convey.Convey("DelLikeListCtime", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
items = []*like.Item{{Sid: 10256, Wid: 55, Mid: 234}}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.DelLikeListCtime(c, sid, items)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeLikeMaxID(t *testing.T) {
convey.Convey("LikeMaxID", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.LikeMaxID(c)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", res)
})
})
})
}
func TestLikeStoryLikeSum(t *testing.T) {
convey.Convey("StoryLikeSum", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
mid = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.StoryLikeSum(c, sid, mid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeIncrStoryLikeSum(t *testing.T) {
convey.Convey("IncrStoryLikeSum", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
mid = int64(77)
score = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.IncrStoryLikeSum(c, sid, mid, score)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeSetLikeSum(t *testing.T) {
convey.Convey("SetLikeSum", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
mid = int64(77)
sum = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetLikeSum(c, sid, mid, sum)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
fmt.Printf("%v", err)
})
})
})
}
func TestLikeStoryEachLikeSum(t *testing.T) {
convey.Convey("StoryEachLikeSum", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10296)
mid = int64(216761)
lid = int64(13538)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.StoryEachLikeSum(c, sid, mid, lid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%d", res)
})
})
})
}
func TestLikeIncrStoryEachLikeAct(t *testing.T) {
convey.Convey("IncrStoryEachLikeAct", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
mid = int64(77)
lid = int64(77)
score = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.IncrStoryEachLikeAct(c, sid, mid, lid, score)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeSetEachLikeSum(t *testing.T) {
convey.Convey("SetEachLikeSum", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
mid = int64(77)
lid = int64(77)
sum = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetEachLikeSum(c, sid, mid, lid, sum)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
fmt.Printf("%v", err)
})
})
})
}
func TestLikeCtime(t *testing.T) {
convey.Convey("SetEachLikeSum", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10365)
start = 1
end = 100
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.LikeCtime(c, sid, start, end)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%v", res)
})
})
})
}
func TestLikeRandom(t *testing.T) {
convey.Convey("SetEachLikeSum", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10365)
start = 1
end = 100
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.LikeRandom(c, sid, start, end)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%v", res)
})
})
})
}
func TestLikeRandomCount(t *testing.T) {
convey.Convey("SetEachLikeSum", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10365)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.LikeRandomCount(c, sid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%v", res)
})
})
})
}
func TestSetLikeRandom(t *testing.T) {
convey.Convey("SetEachLikeSum", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10365)
ids = []int64{2354, 2355}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.SetLikeRandom(c, sid, ids)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeCount(t *testing.T) {
convey.Convey("SetEachLikeSum", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10365)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.LikeCount(c, sid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%v", res)
})
})
})
}
func TestDao_SourceItemData(t *testing.T) {
convey.Convey("test group item data", t, func(ctx convey.C) {
sid := int64(37)
data, err := d.SourceItemData(context.Background(), sid)
convey.So(err, convey.ShouldBeNil)
str, _ := json.Marshal(data)
convey.Printf("%+v", string(str))
})
}
func TestDao_ListFromES(t *testing.T) {
convey.Convey("test group item data", t, func(ctx convey.C) {
sid := int64(1)
ps := 100
pn := 1
data, err := d.ListFromES(context.Background(), sid, "", ps, pn, time.Now().Unix())
convey.So(err, convey.ShouldBeNil)
for _, v := range data.List {
convey.Printf(" %+v ", v.Item)
}
})
}
func TestDao_MultiTags(t *testing.T) {
convey.Convey("test group item data", t, func(ctx convey.C) {
wids := []int64{10109984}
data, err := d.MultiTags(context.Background(), wids)
convey.So(err, convey.ShouldBeNil)
convey.Printf("%+v", data)
})
}
func TestDao_OidInfoFromES(t *testing.T) {
convey.Convey("test group item data", t, func(ctx convey.C) {
oids := []int64{11, 21}
stype := 1
data, err := d.OidInfoFromES(context.Background(), oids, stype)
convey.So(err, convey.ShouldBeNil)
convey.Printf("%+v", data)
})
}

View File

@@ -0,0 +1,45 @@
package like
import (
"context"
"net/url"
"strconv"
l "go-common/app/interface/main/activity/model/like"
"go-common/library/ecode"
"go-common/library/net/metadata"
"github.com/pkg/errors"
)
// AddLotteryTimes .
func (d *Dao) AddLotteryTimes(c context.Context, sid, mid int64) (err error) {
params := url.Values{}
params.Set("act_id", strconv.FormatInt(sid, 10))
params.Set("mid", strconv.FormatInt(mid, 10))
var res struct {
Code int `json:"code"`
}
if err = d.client.Get(c, d.addLotteryTimesURL, metadata.String(c, metadata.RemoteIP), params, &res); err != nil {
err = errors.Wrapf(err, "d.client.Get(%s)", d.addLotteryTimesURL+"?"+params.Encode())
return
}
if res.Code != ecode.OK.Code() {
err = ecode.Int(res.Code)
}
return
}
// LotteryIndex .
func (d *Dao) LotteryIndex(c context.Context, actID, platform, source, mid int64) (res *l.Lottery, err error) {
params := url.Values{}
params.Set("act_id", strconv.FormatInt(actID, 10))
params.Set("platform", strconv.FormatInt(platform, 10))
params.Set("source", strconv.FormatInt(source, 10))
params.Set("mid", strconv.FormatInt(mid, 10))
res = new(l.Lottery)
if err = d.client.Get(c, d.lotteryIndexURL, metadata.String(c, metadata.RemoteIP), params, &res); err != nil {
err = errors.Wrapf(err, "d.client.NewRequest(%s)", d.lotteryIndexURL)
}
return
}

View File

@@ -0,0 +1,45 @@
package like
import (
"context"
"testing"
"fmt"
"github.com/smartystreets/goconvey/convey"
)
func TestLikeLotteryIndex(t *testing.T) {
convey.Convey("LotteryIndex", t, func(ctx convey.C) {
var (
c = context.Background()
actID = int64(1)
platform = int64(1)
source = int64(1)
mid = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.LotteryIndex(c, actID, platform, source, mid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
fmt.Printf("%+v", err)
fmt.Printf("%+v", res)
})
})
})
}
func TestAddLotteryTimes(t *testing.T) {
convey.Convey("LotteryIndex", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(1)
mid = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddLotteryTimes(c, sid, mid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
fmt.Printf("%+v", err)
})
})
})
}

View File

@@ -0,0 +1,143 @@
package like
import (
"context"
"database/sql"
"fmt"
match "go-common/app/interface/main/activity/model/like"
xsql "go-common/library/database/sql"
"go-common/library/log"
"go-common/library/xstr"
)
const (
_matchSidSQL = "SELECT id,sid,max_stake,stake,name,url,cover,ctime,mtime FROM act_matchs WHERE status=0 AND sid = ? order by id"
_matchSQL = "SELECT id,sid,max_stake,stake,name,url,cover,ctime,mtime FROM act_matchs WHERE status=0 AND id = ?"
_objIDSQL = "SELECT id,match_id,sid,home_name,home_logo,home_score,away_name,away_logo,away_score,result,ctime,mtime,stime,etime,game_stime FROM act_matchs_object WHERE status=0 AND id= ?"
_objIDsSQL = "SELECT id,match_id,sid,home_name,home_logo,home_score,away_name,away_logo,away_score,result,ctime,mtime,stime,etime,game_stime FROM act_matchs_object WHERE status=0 AND id IN (%s)"
_objSIDSQL = "SELECT o.id,o.match_id,o.sid,o.home_name,o.home_logo,o.home_score,o.away_name,o.away_logo,o.away_score,o.result,o.ctime,o.mtime,o.stime,o.etime,o.game_stime,m.name as match_name FROM act_matchs_object as o INNER JOIN act_matchs as m ON o.match_id=m.id WHERE o.status=0 AND o.result=0 AND o.sid= ? ORDER BY o.game_stime ASC"
_userAddSQL = "INSERT INTO act_match_user_log (mid,match_id,m_o_id,sid,result,stake) VALUES (?,?,?,?,?,?)"
_userResultSQL = "SELECT id,mid,match_id,m_o_id,sid,result,stake,ctime,mtime FROM act_match_user_log WHERE sid = ? AND mid = ? ORDER BY id DESC"
)
// Match get Match
func (d *Dao) Match(c context.Context, id int64) (res *match.Match, err error) {
res = &match.Match{}
row := d.db.QueryRow(c, _matchSQL, id)
if err = row.Scan(&res.ID, &res.Sid, &res.MaxStake, &res.Stake, &res.Name, &res.Url, &res.Cover, &res.Ctime, &res.Mtime); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
log.Error("Match:row.Scan error(%v)", err)
}
}
return
}
// ActMatch get Activity Match
func (d *Dao) ActMatch(c context.Context, sid int64) (res []*match.Match, err error) {
var (
rows *xsql.Rows
matchs []*match.Match
)
if rows, err = d.db.Query(c, _matchSidSQL, sid); err != nil {
log.Error("Match: db.Exec(%d) error(%v)", sid, err)
return
}
defer rows.Close()
for rows.Next() {
r := new(match.Match)
if err = rows.Scan(&r.ID, &r.Sid, &r.MaxStake, &r.Stake, &r.Name, &r.Url, &r.Cover, &r.Ctime, &r.Mtime); err != nil {
log.Error("Match:row.Scan() error(%v)", err)
return
}
matchs = append(matchs, r)
}
res = matchs
return
}
// Object get object
func (d *Dao) Object(c context.Context, id int64) (res *match.Object, err error) {
res = &match.Object{}
row := d.db.QueryRow(c, _objIDSQL, id)
if err = row.Scan(&res.ID, &res.MatchId, &res.Sid, &res.HomeName, &res.HomeLogo, &res.HomeScore, &res.AwayName, &res.AwayLogo, &res.AwayScore, &res.Result, &res.Ctime, &res.Mtime, &res.Stime, &res.Etime, &res.GameStime); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
log.Error("Match:row.Scan error(%v)", err)
}
}
return
}
// RawMatchSubjects .
func (d *Dao) RawMatchSubjects(c context.Context, ids []int64) (res map[int64]*match.Object, err error) {
var rows *xsql.Rows
if rows, err = d.db.Query(c, fmt.Sprintf(_objIDsSQL, xstr.JoinInts(ids))); err != nil {
log.Error("RawMatchSubjects: d.db.Query(%v) error(%v)", ids, err)
return
}
defer rows.Close()
res = make(map[int64]*match.Object, len(ids))
for rows.Next() {
r := new(match.Object)
if err = rows.Scan(&r.ID, &r.MatchId, &r.Sid, &r.HomeName, &r.HomeLogo, &r.HomeScore, &r.AwayName, &r.AwayLogo, &r.AwayScore, &r.Result, &r.Ctime, &r.Mtime, &r.Stime, &r.Etime, &r.GameStime); err != nil {
log.Error("RawMatchSubjects:row.Scan() error(%v)", err)
return
}
res[r.ID] = r
}
return
}
// ObjectsUnStart get unstart objects.
func (d *Dao) ObjectsUnStart(c context.Context, sid int64) (res []*match.Object, err error) {
var (
rows *xsql.Rows
)
if rows, err = d.db.Query(c, _objSIDSQL, sid); err != nil {
log.Error("ObjectsUnStart: db.Exec(%d) error(%v)", sid, err)
return
}
defer rows.Close()
for rows.Next() {
r := new(match.Object)
if err = rows.Scan(&r.ID, &r.MatchId, &r.Sid, &r.HomeName, &r.HomeLogo, &r.HomeScore, &r.AwayName, &r.AwayLogo, &r.AwayScore, &r.Result, &r.Ctime, &r.Mtime, &r.Stime, &r.Etime, &r.GameStime, &r.MatchName); err != nil {
log.Error("ObjectsUnStart:row.Scan() error(%v)", err)
return
}
res = append(res, r)
}
return
}
// AddGuess add match user log
func (d *Dao) AddGuess(c context.Context, mid, matID, objID, sid, result, stake int64) (lastID int64, err error) {
var res sql.Result
if res, err = d.db.Exec(c, _userAddSQL, mid, matID, objID, sid, result, stake); err != nil {
log.Error("AddGuess: db.Exec(%d,%d,%d,%d,%d,%d) error(%v)", mid, matID, objID, sid, result, stake, err)
return
}
return res.LastInsertId()
}
// ListGuess get match user log
func (d *Dao) ListGuess(c context.Context, sid, mid int64) (res []*match.UserLog, err error) {
var rows *xsql.Rows
if rows, err = d.db.Query(c, _userResultSQL, sid, mid); err != nil {
log.Error("ListGuess: db.Exec(%d,%d) error(%v)", sid, mid, err)
return
}
defer rows.Close()
for rows.Next() {
r := new(match.UserLog)
if err = rows.Scan(&r.ID, &r.Mid, &r.MatchId, &r.MOId, &r.Sid, &r.Result, &r.Stake, &r.Ctime, &r.Mtime); err != nil {
log.Error("ListGuess:row.Scan() error(%v)", err)
return
}
res = append(res, r)
}
return
}

View File

@@ -0,0 +1,573 @@
package like
import (
"context"
"encoding/json"
"fmt"
match "go-common/app/interface/main/activity/model/like"
"go-common/library/cache/redis"
"go-common/library/log"
"go-common/library/time"
)
const (
_keyMatch = "mat_%d"
_keyActMatch = "am_%d"
_keyObject = "ob_%d"
_keyObjects = "os_%d"
_keyUserLog = "ugl_%d_%d"
_keyMatchFollow = "mf_%d"
)
func keyMatch(id int64) string {
return fmt.Sprintf(_keyMatch, id)
}
func keyActMatch(sid int64) string {
return fmt.Sprintf(_keyActMatch, sid)
}
func keyObject(id int64) string {
return fmt.Sprintf(_keyObject, id)
}
func keyObjects(sid int64) string {
return fmt.Sprintf(_keyObjects, sid)
}
func keyUserLog(sid, mid int64) string {
return fmt.Sprintf(_keyUserLog, sid, mid)
}
func keyMatchFollow(mid int64) string {
return fmt.Sprintf(_keyMatchFollow, mid)
}
// MatchCache get match from cache.
func (d *Dao) MatchCache(c context.Context, id int64) (mat *match.Match, err error) {
var (
bs []byte
key = keyMatch(id)
conn = d.redis.Get(c)
)
defer conn.Close()
if bs, err = redis.Bytes(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
mat = nil
} else {
log.Error("conn.Do(GET,%s) error(%v)", key, err)
}
return
}
mat = new(match.Match)
if err = json.Unmarshal(bs, mat); err != nil {
log.Error("json.Unmarshal(%s) error(%v)", string(bs), err)
}
return
}
// SetMatchCache set match to cache.
func (d *Dao) SetMatchCache(c context.Context, id int64, mat *match.Match) (err error) {
var (
bs []byte
key = keyMatch(id)
conn = d.redis.Get(c)
)
defer conn.Close()
if bs, err = json.Marshal(mat); err != nil {
log.Error("json.Marshal() error(%v)", err)
return
}
if err = conn.Send("SET", key, bs); err != nil {
log.Error("conn.Send(SET,%s,%d) error(%v)", key, id, err)
return
}
if err = conn.Send("EXPIRE", key, d.matchExpire); err != nil {
log.Error("conn.Send(EXPIRE,%s) error(%v)", key, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("add conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("add conn.Receive()%d error(%v)", i+1, err)
return
}
}
return
}
// ActMatchCache get match list from cache.
func (d *Dao) ActMatchCache(c context.Context, sid int64) (res []*match.Match, err error) {
key := keyActMatch(sid)
conn := d.redis.Get(c)
defer conn.Close()
values, err := redis.Values(conn.Do("ZRANGE", key, 0, -1, "WITHSCORES"))
if err != nil {
log.Error("conn.Do(ZRANGE, %s) error(%v)", key, err)
return
}
if len(values) == 0 {
return
}
var num int64
for len(values) > 0 {
bs := []byte{}
if values, err = redis.Scan(values, &bs, &num); err != nil {
log.Error("redis.Scan(%v) error(%v)", values, err)
return
}
match := &match.Match{}
if err = json.Unmarshal(bs, match); err != nil {
log.Error("json.Unmarshal(%v) error(%v)", bs, err)
return
}
res = append(res, match)
}
return
}
// SetActMatchCache set match list cache.
func (d *Dao) SetActMatchCache(c context.Context, sid int64, matchs []*match.Match) (err error) {
key := keyActMatch(sid)
conn := d.redis.Get(c)
defer conn.Close()
count := 0
if err = conn.Send("DEL", key); err != nil {
log.Error("conn.Send(DEL, %s) error(%v)", key, err)
return
}
count++
for _, match := range matchs {
bs, _ := json.Marshal(match)
if err = conn.Send("ZADD", key, match.Ctime, bs); err != nil {
log.Error("conn.Send(ZADD, %s, %s) error(%v)", key, string(bs), err)
return
}
count++
}
if err = conn.Send("EXPIRE", key, d.matchExpire); err != nil {
log.Error("conn.Send(Expire, %s, %d) error(%v)", key, d.matchExpire, err)
return
}
count++
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < count; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}
// ObjectCache get object from cache.
func (d *Dao) ObjectCache(c context.Context, id int64) (mat *match.Object, err error) {
var (
bs []byte
key = keyObject(id)
conn = d.redis.Get(c)
)
defer conn.Close()
if bs, err = redis.Bytes(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
mat = nil
} else {
log.Error("conn.Do(GET,%s) error(%v)", key, err)
}
return
}
mat = new(match.Object)
if err = json.Unmarshal(bs, mat); err != nil {
log.Error("json.Unmarshal(%s) error(%v)", string(bs), err)
}
return
}
// CacheMatchSubjects .
func (d *Dao) CacheMatchSubjects(c context.Context, ids []int64) (res map[int64]*match.Object, err error) {
var (
key string
args = redis.Args{}
bss [][]byte
)
for _, pid := range ids {
key = keyObject(pid)
args = args.Add(key)
}
conn := d.redis.Get(c)
defer conn.Close()
if bss, err = redis.ByteSlices(conn.Do("MGET", args...)); err != nil {
if err == redis.ErrNil {
err = nil
} else {
log.Error("CacheMatchSubjects conn.Do(MGET,%s) error(%v)", key, err)
}
return
}
res = make(map[int64]*match.Object, len(ids))
for _, bs := range bss {
obj := new(match.Object)
if bs == nil {
continue
}
if err = json.Unmarshal(bs, obj); err != nil {
log.Error("CacheMatchSubjects json.Unmarshal(%s) error(%v)", string(bs), err)
err = nil
continue
}
res[obj.ID] = obj
}
return
}
// SetObjectCache set object to cache.
func (d *Dao) SetObjectCache(c context.Context, id int64, object *match.Object) (err error) {
var (
bs []byte
key = keyObject(id)
conn = d.redis.Get(c)
)
defer conn.Close()
if bs, err = json.Marshal(object); err != nil {
log.Error("json.Marshal() error(%v)", err)
return
}
if err = conn.Send("SET", key, bs); err != nil {
log.Error("conn.Send(HSET,%s,%d) error(%v)", key, id, err)
return
}
if err = conn.Send("EXPIRE", key, d.matchExpire); err != nil {
log.Error("conn.Send(EXPIRE,%s) error(%v)", key, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("add conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("add conn.Receive()%d error(%v)", i+1, err)
return
}
}
return
}
// AddCacheMatchSubjects .
func (d *Dao) AddCacheMatchSubjects(c context.Context, data map[int64]*match.Object) (err error) {
if len(data) == 0 {
return
}
var (
bs []byte
keyID string
keyIDs []string
argsPid = redis.Args{}
)
conn := d.redis.Get(c)
defer conn.Close()
for _, v := range data {
if bs, err = json.Marshal(v); err != nil {
log.Error("json.Marshal err(%v)", err)
continue
}
keyID = keyObject(v.ID)
keyIDs = append(keyIDs, keyID)
argsPid = argsPid.Add(keyID).Add(string(bs))
}
if err = conn.Send("MSET", argsPid...); err != nil {
log.Error("AddCacheMatchSubjects conn.Send(MSET) error(%v)", err)
return
}
count := 1
for _, v := range keyIDs {
count++
if err = conn.Send("EXPIRE", v, d.matchExpire); err != nil {
log.Error("AddCacheMatchSubjects conn.Send(Expire, %s, %d) error(%v)", v, d.matchExpire, err)
return
}
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < count; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}
// ObjectsCache get object list from cache.
func (d *Dao) ObjectsCache(c context.Context, sid int64, start, end int) (res []*match.Object, total int, err error) {
key := keyObjects(sid)
conn := d.redis.Get(c)
defer conn.Close()
values, err := redis.Values(conn.Do("ZRANGE", key, start, end, "WITHSCORES"))
if err != nil {
log.Error("conn.Do(ZRANGE, %s) error(%v)", key, err)
return
}
if len(values) == 0 {
return
}
var num int64
for len(values) > 0 {
bs := []byte{}
if values, err = redis.Scan(values, &bs, &num); err != nil {
log.Error("redis.Scan(%v) error(%v)", values, err)
return
}
object := &match.Object{}
if err = json.Unmarshal(bs, object); err != nil {
log.Error("json.Unmarshal(%v) error(%v)", bs, err)
return
}
res = append(res, object)
}
total = from(num)
return
}
// SetObjectsCache set object list cache.
func (d *Dao) SetObjectsCache(c context.Context, sid int64, objects []*match.Object, total int) (err error) {
key := keyObjects(sid)
conn := d.redis.Get(c)
defer conn.Close()
count := 0
if err = conn.Send("DEL", key); err != nil {
log.Error("conn.Send(DEL, %s) error(%v)", key, err)
return
}
count++
for _, object := range objects {
bs, _ := json.Marshal(object)
if err = conn.Send("ZADD", key, combine(object.GameStime, total), bs); err != nil {
log.Error("conn.Send(ZADD, %s, %s) error(%v)", key, string(bs), err)
return
}
count++
}
if err = conn.Send("EXPIRE", key, d.matchExpire); err != nil {
log.Error("conn.Send(Expire, %s, %d) error(%v)", key, d.matchExpire, err)
return
}
count++
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < count; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}
// UserLogCache get user log list from cache.
func (d *Dao) UserLogCache(c context.Context, sid, mid int64) (res []*match.UserLog, err error) {
key := keyUserLog(sid, mid)
conn := d.redis.Get(c)
defer conn.Close()
values, err := redis.Values(conn.Do("ZREVRANGE", key, 0, -1, "WITHSCORES"))
if err != nil {
log.Error("conn.Do(ZREVRANGE, %s) error(%v)", key, err)
return
}
if len(values) == 0 {
return
}
var num int64
for len(values) > 0 {
bs := []byte{}
if values, err = redis.Scan(values, &bs, &num); err != nil {
log.Error("redis.Scan(%v) error(%v)", values, err)
return
}
userLog := &match.UserLog{}
if err = json.Unmarshal(bs, userLog); err != nil {
log.Error("json.Unmarshal(%v) error(%v)", bs, err)
return
}
res = append(res, userLog)
}
return
}
// SetUserLogCache set user log list cache.
func (d *Dao) SetUserLogCache(c context.Context, sid, mid int64, userLogs []*match.UserLog) (err error) {
key := keyUserLog(sid, mid)
conn := d.redis.Get(c)
defer conn.Close()
count := 0
if err = conn.Send("DEL", key); err != nil {
log.Error("conn.Send(DEL, %s) error(%v)", key, err)
return
}
count++
for _, userLog := range userLogs {
bs, _ := json.Marshal(userLog)
if err = conn.Send("ZADD", key, userLog.Ctime, bs); err != nil {
log.Error("conn.Send(ZADD, %s, %s) error(%v)", key, string(bs), err)
return
}
count++
}
if err = conn.Send("EXPIRE", key, d.matchExpire); err != nil {
log.Error("conn.Send(Expire, %s, %d) error(%v)", key, d.matchExpire, err)
return
}
count++
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < count; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}
// DelUserLogCache delete user log cache.
func (d *Dao) DelUserLogCache(c context.Context, sid, mid int64) (err error) {
key := keyUserLog(sid, mid)
conn := d.redis.Get(c)
defer conn.Close()
_, err = conn.Do("DEL", key)
return
}
// DelActMatchCache del match cache
func (d *Dao) DelActMatchCache(c context.Context, sid, matID int64) (err error) {
matKey := keyMatch(matID)
actMKey := keyActMatch(sid)
conn := d.redis.Get(c)
defer conn.Close()
if err = conn.Send("DEL", matKey); err != nil {
log.Error("conn.Send(DEL, %s) error(%v)", actMKey, err)
return
}
if err = conn.Send("DEL", actMKey); err != nil {
log.Error("conn.Send(DEL, %s) error(%v)", actMKey, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush() error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}
// DelObjectCache del object cache
func (d *Dao) DelObjectCache(c context.Context, objID, sid int64) (err error) {
objKey := keyObject(objID)
objsKey := keyObjects(sid)
conn := d.redis.Get(c)
defer conn.Close()
if err = conn.Send("DEL", objKey); err != nil {
log.Error("conn.Send(DEL, %s) error(%v)", objKey, err)
return
}
if err = conn.Send("DEL", objsKey); err != nil {
log.Error("conn.Send(DEL, %s) error(%v)", objKey, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush() error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}
// AddFollow add follow teams
func (d *Dao) AddFollow(c context.Context, mid int64, teams []string) (err error) {
var (
bs []byte
key = keyMatchFollow(mid)
conn = d.redis.Get(c)
)
defer conn.Close()
if bs, err = json.Marshal(teams); err != nil {
log.Error("json.Marshal() error(%v)", err)
return
}
if err = conn.Send("SET", key, bs); err != nil {
log.Error("conn.Send(SET,%s,%d) error(%v)", key, mid, err)
return
}
if err = conn.Send("EXPIRE", key, d.followExpire); err != nil {
log.Error("conn.Send(EXPIRE,%s) error(%v)", key, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("add conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("add conn.Receive()%d error(%v)", i+1, err)
return
}
}
return
}
// Follow get follow teams
func (d *Dao) Follow(c context.Context, mid int64) (res []string, err error) {
var (
bs []byte
key = keyMatchFollow(mid)
conn = d.redis.Get(c)
)
defer conn.Close()
if bs, err = redis.Bytes(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
} else {
log.Error("conn.Do(GET,%s) error(%v)", key, err)
}
return
}
if err = json.Unmarshal(bs, &res); err != nil {
log.Error("json.Unmarshal(%s) error(%v)", string(bs), err)
}
return
}
func from(i int64) int {
return int(i & 0xffff)
}
func combine(ctime time.Time, count int) int64 {
return ctime.Time().Unix()<<16 | int64(count)
}

View File

@@ -0,0 +1,389 @@
package like
import (
"context"
match "go-common/app/interface/main/activity/model/like"
xtime "go-common/library/time"
"testing"
"time"
"fmt"
"github.com/smartystreets/goconvey/convey"
)
func TestLikekeyMatch(t *testing.T) {
convey.Convey("keyMatch", t, func(ctx convey.C) {
var (
id = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyMatch(id)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikekeyActMatch(t *testing.T) {
convey.Convey("keyActMatch", t, func(ctx convey.C) {
var (
sid = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyActMatch(sid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikekeyObject(t *testing.T) {
convey.Convey("keyObject", t, func(ctx convey.C) {
var (
id = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyObject(id)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikekeyObjects(t *testing.T) {
convey.Convey("keyObjects", t, func(ctx convey.C) {
var (
sid = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyObjects(sid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikekeyUserLog(t *testing.T) {
convey.Convey("keyUserLog", t, func(ctx convey.C) {
var (
sid = int64(10256)
mid = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyUserLog(sid, mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikekeyMatchFollow(t *testing.T) {
convey.Convey("keyMatchFollow", t, func(ctx convey.C) {
var (
mid = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyMatchFollow(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeMatchCache(t *testing.T) {
convey.Convey("MatchCache", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
mat, err := d.MatchCache(c, id)
ctx.Convey("Then err should be nil.mat should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", mat)
})
})
})
}
func TestLikeSetMatchCache(t *testing.T) {
convey.Convey("SetMatchCache", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(10256)
mat = &match.Match{Sid: 10256}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetMatchCache(c, id, mat)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeActMatchCache(t *testing.T) {
convey.Convey("ActMatchCache", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.ActMatchCache(c, sid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", res)
})
})
})
}
func TestLikeSetActMatchCache(t *testing.T) {
convey.Convey("SetActMatchCache", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
matchs = []*match.Match{{Sid: 10256}}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetActMatchCache(c, sid, matchs)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeObjectCache(t *testing.T) {
convey.Convey("ObjectCache", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
mat, err := d.ObjectCache(c, id)
ctx.Convey("Then err should be nil.mat should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", mat)
})
})
})
}
func TestLikeCacheMatchSubjects(t *testing.T) {
convey.Convey("CacheMatchSubjects", t, func(ctx convey.C) {
var (
c = context.Background()
ids = []int64{10256}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.CacheMatchSubjects(c, ids)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeSetObjectCache(t *testing.T) {
convey.Convey("SetObjectCache", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(10256)
object = &match.Object{Sid: 10256}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetObjectCache(c, id, object)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeAddCacheMatchSubjects(t *testing.T) {
convey.Convey("AddCacheMatchSubjects", t, func(ctx convey.C) {
var (
c = context.Background()
data = map[int64]*match.Object{1: {Sid: 1}}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddCacheMatchSubjects(c, data)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeObjectsCache(t *testing.T) {
convey.Convey("ObjectsCache", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
start = int(1)
end = int(2)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, total, err := d.ObjectsCache(c, sid, start, end)
ctx.Convey("Then err should be nil.res,total should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v,%+v", res, total)
})
})
})
}
func TestLikeSetObjectsCache(t *testing.T) {
convey.Convey("SetObjectsCache", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
objects = []*match.Object{{Sid: 10256}}
total = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetObjectsCache(c, sid, objects, total)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeSetUserLogCache(t *testing.T) {
convey.Convey("SetUserLogCache", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
mid = int64(7)
userLogs = []*match.UserLog{{Sid: 10256}}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetUserLogCache(c, sid, mid, userLogs)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeDelUserLogCache(t *testing.T) {
convey.Convey("DelUserLogCache", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
mid = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.DelUserLogCache(c, sid, mid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeDelActMatchCache(t *testing.T) {
convey.Convey("DelActMatchCache", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
matID = int64(7)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.DelActMatchCache(c, sid, matID)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeDelObjectCache(t *testing.T) {
convey.Convey("DelObjectCache", t, func(ctx convey.C) {
var (
c = context.Background()
objID = int64(1)
sid = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.DelObjectCache(c, objID, sid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeAddFollow(t *testing.T) {
convey.Convey("AddFollow", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(77)
teams = []string{"qwe"}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddFollow(c, mid, teams)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeFollow(t *testing.T) {
convey.Convey("Follow", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.Follow(c, mid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikefrom(t *testing.T) {
convey.Convey("from", t, func(ctx convey.C) {
var (
i = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := from(i)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikecombine(t *testing.T) {
convey.Convey("combine", t, func(ctx convey.C) {
var (
ctime = xtime.Time(time.Now().Unix())
count = int(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := combine(ctime, count)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,129 @@
package like
import (
"context"
"testing"
"fmt"
"github.com/smartystreets/goconvey/convey"
)
func TestLikeMatch(t *testing.T) {
convey.Convey("Match", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.Match(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", res)
})
})
})
}
func TestLikeActMatch(t *testing.T) {
convey.Convey("ActMatch", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.ActMatch(c, sid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", res)
})
})
})
}
func TestLikeObject(t *testing.T) {
convey.Convey("Object", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.Object(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", res)
})
})
})
}
func TestLikeRawMatchSubjects(t *testing.T) {
convey.Convey("RawMatchSubjects", t, func(ctx convey.C) {
var (
c = context.Background()
ids = []int64{10256}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.RawMatchSubjects(c, ids)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeObjectsUnStart(t *testing.T) {
convey.Convey("ObjectsUnStart", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.ObjectsUnStart(c, sid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", res)
})
})
})
}
func TestLikeAddGuess(t *testing.T) {
convey.Convey("AddGuess", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(77)
matID = int64(7)
objID = int64(7)
sid = int64(10256)
result = int64(7)
stake = int64(7)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
lastID, err := d.AddGuess(c, mid, matID, objID, sid, result, stake)
ctx.Convey("Then err should be nil.lastID should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(lastID, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeListGuess(t *testing.T) {
convey.Convey("ListGuess", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10256)
mid = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.ListGuess(c, sid, mid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,894 @@
// Code generated by $GOPATH/src/go-common/app/tool/cache/mc. DO NOT EDIT.
/*
Package like is a generated mc cache package.
It is generated from:
type _mc interface {
// mc: -key=likeKey
CacheLike(c context.Context, id int64) (*likemdl.Item, error)
// mc: -key=likeKey
CacheLikes(c context.Context, id []int64) (map[int64]*likemdl.Item, error)
// mc: -key=likeKey -expire=d.mcPerpetualExpire -encode=json
AddCacheLikes(c context.Context, items map[int64]*likemdl.Item) error
// mc: -key=likeKey -expire=d.mcPerpetualExpire -encode=json
AddCacheLike(c context.Context, key int64, value *likemdl.Item) error
// mc: -key=actSubjectKey
CacheActSubject(c context.Context, id int64) (*likemdl.SubjectItem, error)
// mc: -key=actSubjectKey -expire=d.mcPerpetualExpire -encode=pb
AddCacheActSubject(c context.Context, key int64, value *likemdl.SubjectItem) error
// mc: -key=actSubjectMaxIDKey
CacheActSubjectMaxID(c context.Context) (res int64, err error)
// mc: -key=actSubjectMaxIDKey -expire=d.mcPerpetualExpire -encode=raw
AddCacheActSubjectMaxID(c context.Context, sid int64) error
// mc: -key=likeMaxIDKey
CacheLikeMaxID(c context.Context) (res int64, err error)
// mc: -key=likeMaxIDKey -expire=d.mcPerpetualExpire -encode=raw
AddCacheLikeMaxID(c context.Context, lid int64) error
//mc: -key=likeMissionBuffKey
CacheLikeMissionBuff(c context.Context, sid int64, mid int64) (res int64, err error)
//mc: -key=likeMissionBuffKey
AddCacheLikeMissionBuff(c context.Context, sid int64, val int64, mid int64) error
//mc: -key=likeMissionGroupIDkey
CacheMissionGroupItems(ctx context.Context, lids []int64) (map[int64]*likemdl.MissionGroup, error)
//mc: -key=likeMissionGroupIDkey -expire=d.mcItemExpire -encode=pb
AddCacheMissionGroupItems(ctx context.Context, val map[int64]*likemdl.MissionGroup) error
//mc: -key=likeActMissionKey
CacheActMission(c context.Context, sid int64, lid int64, mid int64) (res int64, err error)
//mc: -key=likeActMissionKey -expire=d.mcPerpetualExpire -encode=raw
AddCacheActMission(c context.Context, sid int64, val int64, lid int64, mid int64) error
//mc: -key=actAchieveKey
CacheActLikeAchieves(c context.Context, sid int64) (res *likemdl.Achievements, err error)
//mc: -key=actAchieveKey -expire=d.mcItemExpire -encode=pb
AddCacheActLikeAchieves(c context.Context, sid int64, res *likemdl.Achievements) error
//mc: -key=actMissionFriendsKey
CacheActMissionFriends(c context.Context, sid int64, lid int64) (res *likemdl.ActMissionGroups, err error)
//mc: -key=actMissionFriendsKey
DelCacheActMissionFriends(c context.Context, sid int64, lid int64) error
//mc: -key=actMissionFriendsKey -expire=d.mcItemExpire -encode=pb
AddCacheActMissionFriends(c context.Context, sid int64, res *likemdl.ActMissionGroups, lid int64) error
//mc: -key=actUserAchieveKey
CacheActUserAchieve(c context.Context, id int64) (res *likemdl.ActLikeUserAchievement, err error)
//mc: -key=actUserAchieveKey -expire=d.mcItemExpire -encode=pb
AddCacheActUserAchieve(c context.Context, id int64, val *likemdl.ActLikeUserAchievement) error
//mc: -key=actUserAchieveAwardKey
CacheActUserAward(c context.Context, id int64) (res int64, err error)
//mc: -key=actUserAchieveAwardKey -expire=d.mcPerpetualExpire -encode=raw
AddCacheActUserAward(c context.Context, id int64, val int64) error
// mc: -key=subjectStatKey
CacheSubjectStat(c context.Context, sid int64) (*likemdl.SubjectStat, error)
// mc: -key=subjectStatKey -expire=d.mcSubStatExpire -encode=json
AddCacheSubjectStat(c context.Context, sid int64, value *likemdl.SubjectStat) error
// mc: -key=viewRankKey
CacheViewRank(c context.Context, sid int64) (string, error)
// mc: -key=viewRankKey -expire=d.mcViewRankExpire -encode=raw
AddCacheViewRank(c context.Context, sid int64, value string) error
// mc: -key=likeContentKey
CacheLikeContent(c context.Context, lids []int64) (res map[int64]*likemdl.LikeContent, err error)
// mc: -key=likeContentKey -expire=d.mcPerpetualExpire -encode=pb
AddCacheLikeContent(c context.Context, val map[int64]*likemdl.LikeContent) error
// mc: -key=sourceItemKey
CacheSourceItemData(c context.Context, sid int64) ([]int64, error)
// mc: -key=sourceItemKey -expire=d.mcSourceItemExpire -encode=json
AddCacheSourceItemData(c context.Context, sid int64, lids []int64) error
// mc: -key=subjectProtocolKey
CacheActSubjectProtocol(c context.Context, sid int64) (res *likemdl.ActSubjectProtocol, err error)
// mc: -key=subjectProtocolKey -expire=d.mcProtocolExpire -encode=pb
AddCacheActSubjectProtocol(c context.Context, sid int64, value *likemdl.ActSubjectProtocol) error
}
*/
package like
import (
"context"
"fmt"
"strconv"
likemdl "go-common/app/interface/main/activity/model/like"
"go-common/library/cache/memcache"
"go-common/library/log"
"go-common/library/stat/prom"
)
var _ _mc
// CacheLike get data from mc
func (d *Dao) CacheLike(c context.Context, id int64) (res *likemdl.Item, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := likeKey(id)
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheLike")
log.Errorv(c, log.KV("CacheLike", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = &likemdl.Item{}
err = conn.Scan(reply, res)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheLike")
log.Errorv(c, log.KV("CacheLike", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// CacheLikes get data from mc
func (d *Dao) CacheLikes(c context.Context, ids []int64) (res map[int64]*likemdl.Item, err error) {
l := len(ids)
if l == 0 {
return
}
keysMap := make(map[string]int64, l)
keys := make([]string, 0, l)
for _, id := range ids {
key := likeKey(id)
keysMap[key] = id
keys = append(keys, key)
}
conn := d.mc.Get(c)
defer conn.Close()
replies, err := conn.GetMulti(keys)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheLikes")
log.Errorv(c, log.KV("CacheLikes", fmt.Sprintf("%+v", err)), log.KV("keys", keys))
return
}
for key, reply := range replies {
var v *likemdl.Item
v = &likemdl.Item{}
err = conn.Scan(reply, v)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheLikes")
log.Errorv(c, log.KV("CacheLikes", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
if res == nil {
res = make(map[int64]*likemdl.Item, len(keys))
}
res[keysMap[key]] = v
}
return
}
// AddCacheLikes Set data to mc
func (d *Dao) AddCacheLikes(c context.Context, values map[int64]*likemdl.Item) (err error) {
if len(values) == 0 {
return
}
conn := d.mc.Get(c)
defer conn.Close()
for id, val := range values {
key := likeKey(id)
item := &memcache.Item{Key: key, Object: val, Expiration: d.mcPerpetualExpire, Flags: memcache.FlagJSON}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheLikes")
log.Errorv(c, log.KV("AddCacheLikes", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
}
return
}
// AddCacheLike Set data to mc
func (d *Dao) AddCacheLike(c context.Context, id int64, val *likemdl.Item) (err error) {
if val == nil {
return
}
conn := d.mc.Get(c)
defer conn.Close()
key := likeKey(id)
item := &memcache.Item{Key: key, Object: val, Expiration: d.mcPerpetualExpire, Flags: memcache.FlagJSON}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheLike")
log.Errorv(c, log.KV("AddCacheLike", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// CacheActSubject get data from mc
func (d *Dao) CacheActSubject(c context.Context, id int64) (res *likemdl.SubjectItem, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := actSubjectKey(id)
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheActSubject")
log.Errorv(c, log.KV("CacheActSubject", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = &likemdl.SubjectItem{}
err = conn.Scan(reply, res)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheActSubject")
log.Errorv(c, log.KV("CacheActSubject", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// AddCacheActSubject Set data to mc
func (d *Dao) AddCacheActSubject(c context.Context, id int64, val *likemdl.SubjectItem) (err error) {
if val == nil {
return
}
conn := d.mc.Get(c)
defer conn.Close()
key := actSubjectKey(id)
item := &memcache.Item{Key: key, Object: val, Expiration: d.mcPerpetualExpire, Flags: memcache.FlagProtobuf}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheActSubject")
log.Errorv(c, log.KV("AddCacheActSubject", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// CacheActSubjectMaxID get data from mc
func (d *Dao) CacheActSubjectMaxID(c context.Context) (res int64, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := actSubjectMaxIDKey()
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheActSubjectMaxID")
log.Errorv(c, log.KV("CacheActSubjectMaxID", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
var v string
err = conn.Scan(reply, &v)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheActSubjectMaxID")
log.Errorv(c, log.KV("CacheActSubjectMaxID", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
r, err := strconv.ParseInt(v, 10, 64)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheActSubjectMaxID")
log.Errorv(c, log.KV("CacheActSubjectMaxID", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = int64(r)
return
}
// AddCacheActSubjectMaxID Set data to mc
func (d *Dao) AddCacheActSubjectMaxID(c context.Context, val int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := actSubjectMaxIDKey()
bs := []byte(strconv.FormatInt(int64(val), 10))
item := &memcache.Item{Key: key, Value: bs, Expiration: d.mcPerpetualExpire, Flags: memcache.FlagRAW}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheActSubjectMaxID")
log.Errorv(c, log.KV("AddCacheActSubjectMaxID", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// CacheLikeMaxID get data from mc
func (d *Dao) CacheLikeMaxID(c context.Context) (res int64, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := likeMaxIDKey()
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheLikeMaxID")
log.Errorv(c, log.KV("CacheLikeMaxID", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
var v string
err = conn.Scan(reply, &v)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheLikeMaxID")
log.Errorv(c, log.KV("CacheLikeMaxID", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
r, err := strconv.ParseInt(v, 10, 64)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheLikeMaxID")
log.Errorv(c, log.KV("CacheLikeMaxID", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = int64(r)
return
}
// AddCacheLikeMaxID Set data to mc
func (d *Dao) AddCacheLikeMaxID(c context.Context, val int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := likeMaxIDKey()
bs := []byte(strconv.FormatInt(int64(val), 10))
item := &memcache.Item{Key: key, Value: bs, Expiration: d.mcPerpetualExpire, Flags: memcache.FlagRAW}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheLikeMaxID")
log.Errorv(c, log.KV("AddCacheLikeMaxID", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// CacheLikeMissionBuff get data from mc
func (d *Dao) CacheLikeMissionBuff(c context.Context, id int64, mid int64) (res int64, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := likeMissionBuffKey(id, mid)
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheLikeMissionBuff")
log.Errorv(c, log.KV("CacheLikeMissionBuff", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
var v string
err = conn.Scan(reply, &v)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheLikeMissionBuff")
log.Errorv(c, log.KV("CacheLikeMissionBuff", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
r, err := strconv.ParseInt(v, 10, 64)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheLikeMissionBuff")
log.Errorv(c, log.KV("CacheLikeMissionBuff", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = int64(r)
return
}
// AddCacheLikeMissionBuff Set data to mc
func (d *Dao) AddCacheLikeMissionBuff(c context.Context, id int64, val int64, mid int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := likeMissionBuffKey(id, mid)
bs := []byte(strconv.FormatInt(int64(val), 10))
item := &memcache.Item{Key: key, Value: bs, Expiration: d.mcPerpetualExpire, Flags: memcache.FlagRAW}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheLikeMissionBuff")
log.Errorv(c, log.KV("AddCacheLikeMissionBuff", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// CacheMissionGroupItems get data from mc
func (d *Dao) CacheMissionGroupItems(c context.Context, ids []int64) (res map[int64]*likemdl.MissionGroup, err error) {
l := len(ids)
if l == 0 {
return
}
keysMap := make(map[string]int64, l)
keys := make([]string, 0, l)
for _, id := range ids {
key := likeMissionGroupIDkey(id)
keysMap[key] = id
keys = append(keys, key)
}
conn := d.mc.Get(c)
defer conn.Close()
replies, err := conn.GetMulti(keys)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheMissionGroupItems")
log.Errorv(c, log.KV("CacheMissionGroupItems", fmt.Sprintf("%+v", err)), log.KV("keys", keys))
return
}
for key, reply := range replies {
var v *likemdl.MissionGroup
v = &likemdl.MissionGroup{}
err = conn.Scan(reply, v)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheMissionGroupItems")
log.Errorv(c, log.KV("CacheMissionGroupItems", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
if res == nil {
res = make(map[int64]*likemdl.MissionGroup, len(keys))
}
res[keysMap[key]] = v
}
return
}
// AddCacheMissionGroupItems Set data to mc
func (d *Dao) AddCacheMissionGroupItems(c context.Context, values map[int64]*likemdl.MissionGroup) (err error) {
if len(values) == 0 {
return
}
conn := d.mc.Get(c)
defer conn.Close()
for id, val := range values {
key := likeMissionGroupIDkey(id)
item := &memcache.Item{Key: key, Object: val, Expiration: d.mcItemExpire, Flags: memcache.FlagProtobuf}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheMissionGroupItems")
log.Errorv(c, log.KV("AddCacheMissionGroupItems", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
}
return
}
// CacheActMission get data from mc
func (d *Dao) CacheActMission(c context.Context, id int64, lid int64, mid int64) (res int64, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := likeActMissionKey(id, lid, mid)
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheActMission")
log.Errorv(c, log.KV("CacheActMission", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
var v string
err = conn.Scan(reply, &v)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheActMission")
log.Errorv(c, log.KV("CacheActMission", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
r, err := strconv.ParseInt(v, 10, 64)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheActMission")
log.Errorv(c, log.KV("CacheActMission", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = int64(r)
return
}
// AddCacheActMission Set data to mc
func (d *Dao) AddCacheActMission(c context.Context, id int64, val int64, lid int64, mid int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := likeActMissionKey(id, lid, mid)
bs := []byte(strconv.FormatInt(int64(val), 10))
item := &memcache.Item{Key: key, Value: bs, Expiration: d.mcPerpetualExpire, Flags: memcache.FlagRAW}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheActMission")
log.Errorv(c, log.KV("AddCacheActMission", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// CacheActLikeAchieves get data from mc
func (d *Dao) CacheActLikeAchieves(c context.Context, id int64) (res *likemdl.Achievements, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := actAchieveKey(id)
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheActLikeAchieves")
log.Errorv(c, log.KV("CacheActLikeAchieves", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = &likemdl.Achievements{}
err = conn.Scan(reply, res)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheActLikeAchieves")
log.Errorv(c, log.KV("CacheActLikeAchieves", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// AddCacheActLikeAchieves Set data to mc
func (d *Dao) AddCacheActLikeAchieves(c context.Context, id int64, val *likemdl.Achievements) (err error) {
if val == nil {
return
}
conn := d.mc.Get(c)
defer conn.Close()
key := actAchieveKey(id)
item := &memcache.Item{Key: key, Object: val, Expiration: d.mcItemExpire, Flags: memcache.FlagProtobuf}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheActLikeAchieves")
log.Errorv(c, log.KV("AddCacheActLikeAchieves", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// CacheActMissionFriends get data from mc
func (d *Dao) CacheActMissionFriends(c context.Context, id int64, lid int64) (res *likemdl.ActMissionGroups, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := actMissionFriendsKey(id, lid)
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheActMissionFriends")
log.Errorv(c, log.KV("CacheActMissionFriends", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = &likemdl.ActMissionGroups{}
err = conn.Scan(reply, res)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheActMissionFriends")
log.Errorv(c, log.KV("CacheActMissionFriends", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// DelCacheActMissionFriends delete data from mc
func (d *Dao) DelCacheActMissionFriends(c context.Context, id int64, lid int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := actMissionFriendsKey(id, lid)
if err = conn.Delete(key); err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:DelCacheActMissionFriends")
log.Errorv(c, log.KV("DelCacheActMissionFriends", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// AddCacheActMissionFriends Set data to mc
func (d *Dao) AddCacheActMissionFriends(c context.Context, id int64, val *likemdl.ActMissionGroups, lid int64) (err error) {
if val == nil {
return
}
conn := d.mc.Get(c)
defer conn.Close()
key := actMissionFriendsKey(id, lid)
item := &memcache.Item{Key: key, Object: val, Expiration: d.mcItemExpire, Flags: memcache.FlagProtobuf}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheActMissionFriends")
log.Errorv(c, log.KV("AddCacheActMissionFriends", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// CacheActUserAchieve get data from mc
func (d *Dao) CacheActUserAchieve(c context.Context, id int64) (res *likemdl.ActLikeUserAchievement, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := actUserAchieveKey(id)
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheActUserAchieve")
log.Errorv(c, log.KV("CacheActUserAchieve", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = &likemdl.ActLikeUserAchievement{}
err = conn.Scan(reply, res)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheActUserAchieve")
log.Errorv(c, log.KV("CacheActUserAchieve", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// AddCacheActUserAchieve Set data to mc
func (d *Dao) AddCacheActUserAchieve(c context.Context, id int64, val *likemdl.ActLikeUserAchievement) (err error) {
if val == nil {
return
}
conn := d.mc.Get(c)
defer conn.Close()
key := actUserAchieveKey(id)
item := &memcache.Item{Key: key, Object: val, Expiration: d.mcItemExpire, Flags: memcache.FlagProtobuf}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheActUserAchieve")
log.Errorv(c, log.KV("AddCacheActUserAchieve", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// CacheActUserAward get data from mc
func (d *Dao) CacheActUserAward(c context.Context, id int64) (res int64, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := actUserAchieveAwardKey(id)
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheActUserAward")
log.Errorv(c, log.KV("CacheActUserAward", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
var v string
err = conn.Scan(reply, &v)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheActUserAward")
log.Errorv(c, log.KV("CacheActUserAward", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
r, err := strconv.ParseInt(v, 10, 64)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheActUserAward")
log.Errorv(c, log.KV("CacheActUserAward", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = int64(r)
return
}
// AddCacheActUserAward Set data to mc
func (d *Dao) AddCacheActUserAward(c context.Context, id int64, val int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := actUserAchieveAwardKey(id)
bs := []byte(strconv.FormatInt(int64(val), 10))
item := &memcache.Item{Key: key, Value: bs, Expiration: d.mcPerpetualExpire, Flags: memcache.FlagRAW}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheActUserAward")
log.Errorv(c, log.KV("AddCacheActUserAward", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// CacheSubjectStat get data from mc
func (d *Dao) CacheSubjectStat(c context.Context, id int64) (res *likemdl.SubjectStat, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := subjectStatKey(id)
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheSubjectStat")
log.Errorv(c, log.KV("CacheSubjectStat", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = &likemdl.SubjectStat{}
err = conn.Scan(reply, res)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheSubjectStat")
log.Errorv(c, log.KV("CacheSubjectStat", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// AddCacheSubjectStat Set data to mc
func (d *Dao) AddCacheSubjectStat(c context.Context, id int64, val *likemdl.SubjectStat) (err error) {
if val == nil {
return
}
conn := d.mc.Get(c)
defer conn.Close()
key := subjectStatKey(id)
item := &memcache.Item{Key: key, Object: val, Expiration: d.mcSubStatExpire, Flags: memcache.FlagJSON}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheSubjectStat")
log.Errorv(c, log.KV("AddCacheSubjectStat", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// CacheViewRank get data from mc
func (d *Dao) CacheViewRank(c context.Context, id int64) (res string, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := viewRankKey(id)
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheViewRank")
log.Errorv(c, log.KV("CacheViewRank", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
err = conn.Scan(reply, &res)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheViewRank")
log.Errorv(c, log.KV("CacheViewRank", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// AddCacheViewRank Set data to mc
func (d *Dao) AddCacheViewRank(c context.Context, id int64, val string) (err error) {
if len(val) == 0 {
return
}
conn := d.mc.Get(c)
defer conn.Close()
key := viewRankKey(id)
bs := []byte(val)
item := &memcache.Item{Key: key, Value: bs, Expiration: d.mcViewRankExpire, Flags: memcache.FlagRAW}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheViewRank")
log.Errorv(c, log.KV("AddCacheViewRank", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// CacheLikeContent get data from mc
func (d *Dao) CacheLikeContent(c context.Context, ids []int64) (res map[int64]*likemdl.LikeContent, err error) {
l := len(ids)
if l == 0 {
return
}
keysMap := make(map[string]int64, l)
keys := make([]string, 0, l)
for _, id := range ids {
key := likeContentKey(id)
keysMap[key] = id
keys = append(keys, key)
}
conn := d.mc.Get(c)
defer conn.Close()
replies, err := conn.GetMulti(keys)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheLikeContent")
log.Errorv(c, log.KV("CacheLikeContent", fmt.Sprintf("%+v", err)), log.KV("keys", keys))
return
}
for key, reply := range replies {
var v *likemdl.LikeContent
v = &likemdl.LikeContent{}
err = conn.Scan(reply, v)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheLikeContent")
log.Errorv(c, log.KV("CacheLikeContent", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
if res == nil {
res = make(map[int64]*likemdl.LikeContent, len(keys))
}
res[keysMap[key]] = v
}
return
}
// AddCacheLikeContent Set data to mc
func (d *Dao) AddCacheLikeContent(c context.Context, values map[int64]*likemdl.LikeContent) (err error) {
if len(values) == 0 {
return
}
conn := d.mc.Get(c)
defer conn.Close()
for id, val := range values {
key := likeContentKey(id)
item := &memcache.Item{Key: key, Object: val, Expiration: d.mcPerpetualExpire, Flags: memcache.FlagProtobuf}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheLikeContent")
log.Errorv(c, log.KV("AddCacheLikeContent", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
}
return
}
// CacheSourceItemData get data from mc
func (d *Dao) CacheSourceItemData(c context.Context, id int64) (res []int64, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := sourceItemKey(id)
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheSourceItemData")
log.Errorv(c, log.KV("CacheSourceItemData", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = []int64{}
err = conn.Scan(reply, &res)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheSourceItemData")
log.Errorv(c, log.KV("CacheSourceItemData", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// AddCacheSourceItemData Set data to mc
func (d *Dao) AddCacheSourceItemData(c context.Context, id int64, val []int64) (err error) {
if len(val) == 0 {
return
}
conn := d.mc.Get(c)
defer conn.Close()
key := sourceItemKey(id)
item := &memcache.Item{Key: key, Object: val, Expiration: d.mcSourceItemExpire, Flags: memcache.FlagJSON}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheSourceItemData")
log.Errorv(c, log.KV("AddCacheSourceItemData", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// CacheActSubjectProtocol get data from mc
func (d *Dao) CacheActSubjectProtocol(c context.Context, id int64) (res *likemdl.ActSubjectProtocol, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := subjectProtocolKey(id)
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheActSubjectProtocol")
log.Errorv(c, log.KV("CacheActSubjectProtocol", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = &likemdl.ActSubjectProtocol{}
err = conn.Scan(reply, res)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheActSubjectProtocol")
log.Errorv(c, log.KV("CacheActSubjectProtocol", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// AddCacheActSubjectProtocol Set data to mc
func (d *Dao) AddCacheActSubjectProtocol(c context.Context, id int64, val *likemdl.ActSubjectProtocol) (err error) {
if val == nil {
return
}
conn := d.mc.Get(c)
defer conn.Close()
key := subjectProtocolKey(id)
item := &memcache.Item{Key: key, Object: val, Expiration: d.mcProtocolExpire, Flags: memcache.FlagProtobuf}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheActSubjectProtocol")
log.Errorv(c, log.KV("AddCacheActSubjectProtocol", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}

View File

@@ -0,0 +1,525 @@
package like
import (
"context"
likemdl "go-common/app/interface/main/activity/model/like"
"testing"
"fmt"
"github.com/smartystreets/goconvey/convey"
)
func TestLikeCacheLike(t *testing.T) {
convey.Convey("CacheLike", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.CacheLike(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%v", res)
})
})
})
}
func TestLikeCacheLikes(t *testing.T) {
convey.Convey("CacheLikes", t, func(ctx convey.C) {
var (
c = context.Background()
ids = []int64{1}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.CacheLikes(c, ids)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%v", res)
})
})
})
}
func TestLikeAddCacheLike(t *testing.T) {
convey.Convey("AddCacheLike", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
val = &likemdl.Item{ID: 0}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddCacheLike(c, id, val)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeCacheActSubject(t *testing.T) {
convey.Convey("CacheActSubject", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.CacheActSubject(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%v", res)
})
})
})
}
func TestLikeAddCacheActSubject(t *testing.T) {
convey.Convey("AddCacheActSubject", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
val = &likemdl.SubjectItem{ID: 0}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddCacheActSubject(c, id, val)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeCacheActSubjectMaxID(t *testing.T) {
convey.Convey("CacheActSubjectMaxID", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.CacheActSubjectMaxID(c)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeAddCacheActSubjectMaxID(t *testing.T) {
convey.Convey("AddCacheActSubjectMaxID", t, func(ctx convey.C) {
var (
c = context.Background()
val = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddCacheActSubjectMaxID(c, val)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeCacheLikeMaxID(t *testing.T) {
convey.Convey("CacheLikeMaxID", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.CacheLikeMaxID(c)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeAddCacheLikeMaxID(t *testing.T) {
convey.Convey("AddCacheLikeMaxID", t, func(ctx convey.C) {
var (
c = context.Background()
val = int64(10586)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddCacheLikeMaxID(c, val)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeCacheLikeMissionBuff(t *testing.T) {
convey.Convey("CacheLikeMissionBuff", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(10256)
mid = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.CacheLikeMissionBuff(c, id, mid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeAddCacheLikeMissionBuff(t *testing.T) {
convey.Convey("AddCacheLikeMissionBuff", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(10256)
val = int64(1)
mid = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddCacheLikeMissionBuff(c, id, val, mid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeCacheMissionGroupItems(t *testing.T) {
convey.Convey("CacheMissionGroupItems", t, func(ctx convey.C) {
var (
c = context.Background()
ids = []int64{1, 2}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.CacheMissionGroupItems(c, ids)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeAddCacheMissionGroupItems(t *testing.T) {
convey.Convey("AddCacheMissionGroupItems", t, func(ctx convey.C) {
var (
c = context.Background()
values = map[int64]*likemdl.MissionGroup{1: {ID: 1, Sid: 1}}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddCacheMissionGroupItems(c, values)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeCacheActMission(t *testing.T) {
convey.Convey("CacheActMission", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(10256)
lid = int64(77)
mid = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.CacheActMission(c, id, lid, mid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeAddCacheActMission(t *testing.T) {
convey.Convey("AddCacheActMission", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(10256)
val = int64(1)
lid = int64(77)
mid = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddCacheActMission(c, id, val, lid, mid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeCacheActLikeAchieves(t *testing.T) {
convey.Convey("CacheActLikeAchieves", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.CacheActLikeAchieves(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", res)
})
})
})
}
func TestLikeAddCacheActLikeAchieves(t *testing.T) {
convey.Convey("AddCacheActLikeAchieves", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
val = &likemdl.Achievements{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddCacheActLikeAchieves(c, id, val)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeCacheActMissionFriends(t *testing.T) {
convey.Convey("CacheActMissionFriends", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(10256)
lid = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.CacheActMissionFriends(c, id, lid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", res)
})
})
})
}
func TestLikeDelCacheActMissionFriends(t *testing.T) {
convey.Convey("DelCacheActMissionFriends", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(10256)
lid = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.DelCacheActMissionFriends(c, id, lid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeAddCacheActMissionFriends(t *testing.T) {
convey.Convey("AddCacheActMissionFriends", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
val = &likemdl.ActMissionGroups{}
lid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddCacheActMissionFriends(c, id, val, lid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeCacheActUserAchieve(t *testing.T) {
convey.Convey("CacheActUserAchieve", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.CacheActUserAchieve(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", res)
})
})
})
}
func TestLikeAddCacheActUserAchieve(t *testing.T) {
convey.Convey("AddCacheActUserAchieve", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
val = &likemdl.ActLikeUserAchievement{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddCacheActUserAchieve(c, id, val)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeCacheActUserAward(t *testing.T) {
convey.Convey("CacheActUserAward", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.CacheActUserAward(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeAddCacheActUserAward(t *testing.T) {
convey.Convey("AddCacheActUserAward", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(10256)
val = int64(77)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddCacheActUserAward(c, id, val)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeCacheSubjectStat(t *testing.T) {
convey.Convey("CacheSubjectStat", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.CacheSubjectStat(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", res)
})
})
})
}
func TestLikeAddCacheSubjectStat(t *testing.T) {
convey.Convey("AddCacheSubjectStat", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
val = &likemdl.SubjectStat{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddCacheSubjectStat(c, id, val)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeCacheViewRank(t *testing.T) {
convey.Convey("CacheViewRank", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(10256)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.CacheViewRank(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeAddCacheViewRank(t *testing.T) {
convey.Convey("AddCacheViewRank", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
val = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddCacheViewRank(c, id, val)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeCacheLikeContent(t *testing.T) {
convey.Convey("CacheLikeContent", t, func(ctx convey.C) {
var (
c = context.Background()
ids = []int64{1, 2}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.CacheLikeContent(c, ids)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", res)
})
})
})
}
func TestLikeAddCacheLikeContent(t *testing.T) {
convey.Convey("AddCacheLikeContent", t, func(ctx convey.C) {
var (
c = context.Background()
values map[int64]*likemdl.LikeContent
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddCacheLikeContent(c, values)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeAddCacheSourceItemData(t *testing.T) {
convey.Convey("AddCacheSourceItemData", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(213)
values = []int64{10884, 10883, 10882, 10881, 10880}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddCacheSourceItemData(c, sid, values)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeCacheSourceItemData(t *testing.T) {
convey.Convey("CacheSourceItemData", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(213)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.CacheSourceItemData(c, sid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", res)
})
})
})
}

View File

@@ -0,0 +1,59 @@
package like
import (
"context"
"fmt"
"go-common/app/interface/main/activity/model/like"
"go-common/library/cache/memcache"
"go-common/library/log"
)
const (
_prefixInfo = "m_"
)
func keyInfo(sid int64) string {
return fmt.Sprintf("%s%d", _prefixInfo, sid)
}
// SetInfoCache Dao
func (dao *Dao) SetInfoCache(c context.Context, v *like.Subject, sid int64) (err error) {
if v == nil {
v = &like.Subject{}
}
var (
conn = dao.mc.Get(c)
mckey = keyInfo(sid)
)
defer conn.Close()
if err = conn.Set(&memcache.Item{Key: mckey, Object: v, Flags: memcache.FlagGOB, Expiration: dao.mcLikeExpire}); err != nil {
log.Error("conn.Set error(%v)", err)
return
}
return
}
// InfoCache Dao
func (dao *Dao) InfoCache(c context.Context, sid int64) (v *like.Subject, err error) {
var (
mckey = keyInfo(sid)
conn = dao.mc.Get(c)
item *memcache.Item
)
defer conn.Close()
if item, err = conn.Get(mckey); err != nil {
if err == memcache.ErrNotFound {
err = nil
v = nil
} else {
log.Error("conn.Get error(%v)", err)
}
return
}
if err = conn.Scan(item, &v); err != nil {
log.Error("item.Scan error(%v)", err)
return
}
return
}

View File

@@ -0,0 +1,57 @@
package like
import (
"context"
"go-common/app/interface/main/activity/model/like"
"testing"
"fmt"
"github.com/smartystreets/goconvey/convey"
)
func TestLikekeyInfo(t *testing.T) {
convey.Convey("keyInfo", t, func(ctx convey.C) {
var (
sid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyInfo(sid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeSetInfoCache(t *testing.T) {
convey.Convey("SetInfoCache", t, func(ctx convey.C) {
var (
c = context.Background()
v = &like.Subject{}
sid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetInfoCache(c, v, sid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestLikeInfoCache(t *testing.T) {
convey.Convey("InfoCache", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
v, err := d.InfoCache(c, sid)
ctx.Convey("Then err should be nil.v should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", v)
})
})
})
}

View File

@@ -0,0 +1,69 @@
package like
import (
"context"
"database/sql"
"fmt"
l "go-common/app/interface/main/activity/model/like"
"go-common/library/xstr"
"github.com/pkg/errors"
)
const (
_likeMissionBuffSQL = "select id from like_mission_group where sid = ? and mid = ?"
_likeMissionAddSQL = "insert into like_mission_group (`sid`,`mid`,`state`) values (?,?,?)"
_likeMissionGroupSQL = "select id,sid,mid,state,ctime,mtime from like_mission_group where id in (%s)"
// MissionStateInit the init state
MissionStateInit = 0
)
// RawLikeMissionBuff get mid has .
func (d *Dao) RawLikeMissionBuff(c context.Context, sid, mid int64) (ID int64, err error) {
res := &l.MissionGroup{}
row := d.db.QueryRow(c, _likeMissionBuffSQL, sid, mid)
if err = row.Scan(&res.ID); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
err = errors.Wrap(err, "RawLikeMissionBuff:QueryRow")
return
}
}
ID = res.ID
return
}
// MissionGroupAdd add like_mission_group data .
func (d *Dao) MissionGroupAdd(c context.Context, group *l.MissionGroup) (misID int64, err error) {
var res sql.Result
if res, err = d.db.Exec(c, _likeMissionAddSQL, group.Sid, group.Mid, group.State); err != nil {
err = errors.Wrapf(err, "d.db.Exec(%s)", _likeMissionAddSQL)
return
}
return res.LastInsertId()
}
// RawMissionGroupItems get mission_group item by ids.
func (d *Dao) RawMissionGroupItems(c context.Context, lids []int64) (res map[int64]*l.MissionGroup, err error) {
res = make(map[int64]*l.MissionGroup, len(lids))
rows, err := d.db.Query(c, fmt.Sprintf(_likeMissionGroupSQL, xstr.JoinInts(lids)))
if err != nil {
err = errors.Wrapf(err, "d.db.Query(%s)", _likeMissionGroupSQL)
return
}
defer rows.Close()
for rows.Next() {
n := &l.MissionGroup{}
if err = rows.Scan(&n.ID, &n.Sid, &n.Mid, &n.State, &n.Ctime, &n.Mtime); err != nil {
err = errors.Wrapf(err, "d.db.Scan(%s)", _likeMissionGroupSQL)
return
}
res[n.ID] = n
}
if err = rows.Err(); err != nil {
err = errors.Wrap(err, "RawMissionGroupItem:rows.Err()")
}
return
}

View File

@@ -0,0 +1,60 @@
package like
import (
"context"
l "go-common/app/interface/main/activity/model/like"
"testing"
"fmt"
"github.com/smartystreets/goconvey/convey"
)
func TestLikeRawLikeMissionBuff(t *testing.T) {
convey.Convey("RawLikeMissionBuff", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(0)
mid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
ID, err := d.RawLikeMissionBuff(c, sid, mid)
ctx.Convey("Then err should be nil.ID should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(ID, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeMissionGroupAdd(t *testing.T) {
convey.Convey("MissionGroupAdd", t, func(ctx convey.C) {
var (
c = context.Background()
group = &l.MissionGroup{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
misID, err := d.MissionGroupAdd(c, group)
ctx.Convey("Then err should be nil.misID should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(misID, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeRawMissionGroupItems(t *testing.T) {
convey.Convey("RawMissionGroupItems", t, func(ctx convey.C) {
var (
c = context.Background()
lids = []int64{1, 2}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.RawMissionGroupItems(c, lids)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", res)
})
})
})
}

View File

@@ -0,0 +1,27 @@
package like
import (
"context"
lmdl "go-common/app/interface/main/activity/model/like"
"go-common/library/database/sql"
"go-common/library/log"
)
const (
_actProtocolSQL = "select id,sid,protocol,mtime,ctime,types,tags,pubtime,deltime,editime,hot,bgm_id,paster_id,oids,screen_set from act_subject_protocol where sid = ? limit 1"
)
// RawActSubjectProtocol .
func (dao *Dao) RawActSubjectProtocol(c context.Context, sid int64) (res *lmdl.ActSubjectProtocol, err error) {
row := dao.db.QueryRow(c, _actProtocolSQL, sid)
res = new(lmdl.ActSubjectProtocol)
if err = row.Scan(&res.ID, &res.Sid, &res.Protocol, &res.Mtime, &res.Ctime, &res.Types, &res.Tags, &res.Pubtime, &res.Deltime, &res.Editime, &res.Hot, &res.BgmID, &res.PasterID, &res.Oids, &res.ScreenSet); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
log.Error("RawActSubjectProtocol:row.Scan error(%v)", err)
}
}
return
}

View File

@@ -0,0 +1,26 @@
package like
import (
"context"
"testing"
"fmt"
"github.com/smartystreets/goconvey/convey"
)
func TestRawActSubjectProtocol(t *testing.T) {
convey.Convey("RawLikeMissionBuff", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(10350)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.RawActSubjectProtocol(c, sid)
ctx.Convey("Then err should be nil.ID should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%v", res)
})
})
})
}

View File

@@ -0,0 +1,112 @@
package like
import (
"context"
"fmt"
"go-common/library/cache/redis"
"go-common/library/log"
)
const (
_prefixAttention = "lg_"
)
func redisKey(key string) string {
return _prefixAttention + key
}
// RsSet Dao
func (dao *Dao) RsSet(c context.Context, key string, value string) (ok bool, err error) {
var (
rkey = redisKey(key)
conn = dao.redis.Get(c)
)
defer conn.Close()
if ok, err = redis.Bool(conn.Do("SET", rkey, value)); err != nil {
log.Error("conn.Send(SET, %s, %s) error(%v)", rkey, value, err)
return
}
return
}
// RsGet Dao
func (dao *Dao) RsGet(c context.Context, key string) (res string, err error) {
var (
rkey = redisKey(key)
conn = dao.redis.Get(c)
)
defer conn.Close()
if res, err = redis.String(conn.Do("GET", rkey)); err != nil {
if err == redis.ErrNil {
err = nil
} else {
log.Error("conn.Do(GET %s) error(%v)", rkey, err)
}
}
return
}
// RsSetNX Dao
func (dao *Dao) RsSetNX(c context.Context, key string) (res bool, err error) {
var (
rkey = redisKey(key)
conn = dao.redis.Get(c)
)
defer conn.Close()
if res, err = redis.Bool(conn.Do("SETNX", rkey, "1")); err != nil {
if err == redis.ErrNil {
log.Error("conn.Do(GET key(%s)) error(%v)", rkey, err)
err = nil
} else {
log.Error("conn.Do(GET key(%s)) error(%v)", rkey, err)
return
}
}
fmt.Print(res)
return
}
// Rb Dao
func (dao *Dao) Rb(c context.Context, key string) (res []byte, err error) {
var (
rkey = redisKey(key)
conn = dao.redis.Get(c)
)
defer conn.Close()
if res, err = redis.Bytes(conn.Do("GET", rkey)); err != nil {
if err == redis.ErrNil {
res = nil
err = nil
} else {
log.Error("conn.Do(GET key(%v)) error(%v)", rkey, err)
}
}
return
}
// Incr Dao
func (dao *Dao) Incr(c context.Context, key string) (res bool, err error) {
var (
rkey = redisKey(key)
conn = dao.redis.Get(c)
)
defer conn.Close()
if res, err = redis.Bool(conn.Do("INCR", rkey)); err != nil {
log.Error("conn.Do(INCR key(%s)) error(%v)", rkey, err)
}
return
}
// Incrby Dao
func (dao *Dao) Incrby(c context.Context, key string) (res bool, err error) {
var (
rkey = redisKey(key)
conn = dao.redis.Get(c)
)
defer conn.Close()
if res, err = redis.Bool(conn.Do("INCRBY", rkey, 222)); err != nil {
log.Error("conn.Do(INCRBY key(%s)) error(%v)", rkey, err)
}
return
}

View File

@@ -0,0 +1,102 @@
package like
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestLikeredisKey(t *testing.T) {
convey.Convey("redisKey", t, func(ctx convey.C) {
var (
key = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := redisKey(key)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeRsGet(t *testing.T) {
convey.Convey("RsGet", t, func(ctx convey.C) {
var (
c = context.Background()
key = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.RsGet(c, key)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeRsSetNX(t *testing.T) {
convey.Convey("RsSetNX", t, func(ctx convey.C) {
var (
c = context.Background()
key = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.RsSetNX(c, key)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeRb(t *testing.T) {
convey.Convey("Rb", t, func(ctx convey.C) {
var (
c = context.Background()
key = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.Rb(c, key)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeIncr(t *testing.T) {
convey.Convey("Incr", t, func(ctx convey.C) {
var (
c = context.Background()
key = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.Incr(c, key)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeIncrby(t *testing.T) {
convey.Convey("Incrby", t, func(ctx convey.C) {
var (
c = context.Background()
key = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.Incrby(c, key)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,122 @@
package like
import (
"context"
"fmt"
"time"
"go-common/app/interface/main/activity/model/like"
"go-common/library/database/sql"
"go-common/library/log"
"go-common/library/xstr"
"github.com/pkg/errors"
)
const (
_selSubjectSQL = "SELECT s.id,s.name,s.dic,s.cover,s.stime,f.interval,f.ltime,f.tlimit FROM act_subject s INNER JOIN act_time_config f ON s.id=f.sid WHERE s.id = ?"
_votLogSQL = "INSERT INTO act_online_vote_log(sid,aid,mid,stage,vote) VALUES(?,?,?,?,?)"
_subjectNewestSQL = "SELECT id,ctime FROM act_subject WHERE state = 1 AND type IN (%s) AND stime <= ? AND etime >= ? ORDER BY ctime DESC LIMIT 1"
_actSubjectSQL = "SELECT id,name,dic,cover,stime,etime,flag,type,lstime,letime,act_url,uetime,ustime,level,h5_cover,rank,author,oid,state,ctime,mtime,like_limit,android_url,ios_url,daily_like_limit,daily_single_like_limit FROM act_subject WHERE id = ? and state = 1"
_subjectInitSQL = "SELECT id,name,dic,cover,stime,etime,flag,type,lstime,letime,act_url,uetime,ustime,level,h5_cover,rank,author,oid,state,ctime,mtime,like_limit,android_url,ios_url,daily_like_limit,daily_single_like_limit FROM act_subject WHERE id > ? order by id asc limit 1000"
_subjectMaxIDSQL = "SELECT id FROM act_subject order by id desc limit 1"
//SubjectValidState act_subject valid state
SubjectValidState = 1
)
// Subject Dao sql
func (dao *Dao) Subject(c context.Context, sid int64) (n *like.Subject, err error) {
rows := dao.subjectStmt.QueryRow(c, sid)
n = &like.Subject{}
if err = rows.Scan(&n.ID, &n.Name, &n.Dic, &n.Cover, &n.Stime, &n.Interval, &n.Ltime, &n.Tlimit); err != nil {
if err == sql.ErrNoRows {
n = nil
err = nil
} else {
log.Error("row.Scan error(%v)", err)
}
return
}
return
}
// VoteLog Dao sql
func (dao *Dao) VoteLog(c context.Context, sid int64, aid int64, mid int64, stage int64, vote int64) (rows int64, err error) {
rs, err := dao.voteLogStmt.Exec(c, sid, aid, mid, stage, vote)
if err != nil {
log.Error("d.VoteLog.Exec(%d, %d,%d, %d, %d) error(%v)", sid, aid, mid, stage, vote, err)
return
}
rows, err = rs.RowsAffected()
return
}
// NewestSubject get newest subject list.
func (dao *Dao) NewestSubject(c context.Context, typeIDs []int64) (res *like.SubItem, err error) {
res = new(like.SubItem)
now := time.Now()
row := dao.db.QueryRow(c, fmt.Sprintf(_subjectNewestSQL, xstr.JoinInts(typeIDs)), now, now)
if err = row.Scan(&res.ID, &res.Ctime); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
err = errors.Wrap(err, "NewestPage:QueryRow")
}
}
return
}
// RawActSubject get act_subject by id .
func (dao *Dao) RawActSubject(c context.Context, id int64) (res *like.SubjectItem, err error) {
res = new(like.SubjectItem)
row := dao.db.QueryRow(c, _actSubjectSQL, id)
if err = row.Scan(&res.ID, &res.Name, &res.Dic, &res.Cover, &res.Stime, &res.Etime, &res.Flag, &res.Type, &res.Lstime, &res.Letime, &res.ActURL, &res.Uetime, &res.Ustime, &res.Level, &res.H5Cover, &res.Rank, &res.Author, &res.Oid, &res.State, &res.Ctime, &res.Mtime, &res.LikeLimit, &res.AndroidURL, &res.IosURL, &res.DailyLikeLimit, &res.DailySingleLikeLimit); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
err = errors.Wrap(err, "ActSubject:QueryRow")
}
}
return
}
// SubjectListMoreSid get subject more sid .
func (dao *Dao) SubjectListMoreSid(c context.Context, minSid int64) (res []*like.SubjectItem, err error) {
var rows *sql.Rows
if rows, err = dao.db.Query(c, _subjectInitSQL, minSid); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
err = errors.Wrap(err, "SubjectInitialize:dao.db.Query()")
}
return
}
defer rows.Close()
res = make([]*like.SubjectItem, 0, 1000)
for rows.Next() {
a := &like.SubjectItem{}
if err = rows.Scan(&a.ID, &a.Name, &a.Dic, &a.Cover, &a.Stime, &a.Etime, &a.Flag, &a.Type, &a.Lstime, &a.Letime, &a.ActURL, &a.Uetime, &a.Ustime, &a.Level, &a.H5Cover, &a.Rank, &a.Author, &a.Oid, &a.State, &a.Ctime, &a.Mtime, &a.LikeLimit, &a.AndroidURL, &a.IosURL, &a.DailyLikeLimit, &a.DailySingleLikeLimit); err != nil {
err = errors.Wrap(err, "SubjectInitialize:rows.Scan()")
return
}
res = append(res, a)
}
if err = rows.Err(); err != nil {
err = errors.Wrap(err, "SubjectInitialize:rows.Err()")
}
return
}
// SubjectMaxID get act_subject max id .
func (dao *Dao) SubjectMaxID(c context.Context) (res *like.SubjectItem, err error) {
res = new(like.SubjectItem)
row := dao.db.QueryRow(c, _subjectMaxIDSQL)
if err = row.Scan(&res.ID); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
err = errors.Wrap(err, "SubjectMaxID:QueryRow")
}
}
return
}

View File

@@ -0,0 +1,93 @@
package like
import (
"context"
"testing"
"fmt"
"github.com/smartystreets/goconvey/convey"
)
func TestLikeVoteLog(t *testing.T) {
convey.Convey("VoteLog", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(0)
aid = int64(0)
mid = int64(0)
stage = int64(0)
vote = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
rows, err := d.VoteLog(c, sid, aid, mid, stage, vote)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeNewestSubject(t *testing.T) {
convey.Convey("NewestSubject", t, func(ctx convey.C) {
var (
c = context.Background()
typeIDs = []int64{10256}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.NewestSubject(c, typeIDs)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
fmt.Printf("%+v", res)
})
})
})
}
func TestLikeRawActSubject(t *testing.T) {
convey.Convey("RawActSubject", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.RawActSubject(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeSubjectListMoreSid(t *testing.T) {
convey.Convey("SubjectListMoreSid", t, func(ctx convey.C) {
var (
c = context.Background()
minSid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.SubjectListMoreSid(c, minSid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeSubjectMaxID(t *testing.T) {
convey.Convey("SubjectMaxID", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.SubjectMaxID(c)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,77 @@
package like
import (
"context"
"database/sql"
l "go-common/app/interface/main/activity/model/like"
"github.com/pkg/errors"
)
const (
_userAchieveSQL = "select id,aid,sid,mid,award from act_like_user_achievements where id = ?"
_userAchieveUpSQL = "update act_like_user_achievements set award = ? where id = ? and award = 0"
_userAchievementAddSQL = "insert into act_like_user_achievements (`aid`,`mid`,`sid`,`award`) values(?,?,?,?)"
_userAchievementSQL = "select id,aid,sid,mid,award from act_like_user_achievements where sid = ? and mid = ? and del = 0"
// AwardNotChange .
AwardNotChange = 0
// AwardHasChange .
AwardHasChange = 1
// AwardNoGet .
AwardNoGet = 2
)
// AddUserAchievment .
func (d *Dao) AddUserAchievment(c context.Context, userAchi *l.ActLikeUserAchievement) (ID int64, err error) {
var res sql.Result
if res, err = d.db.Exec(c, _userAchievementAddSQL, userAchi.Aid, userAchi.Mid, userAchi.Sid, userAchi.Award); err != nil {
err = errors.Wrapf(err, "d.db.Exec(%s)", _userAchievementAddSQL)
return
}
return res.LastInsertId()
}
// UserAchievement .
func (d *Dao) UserAchievement(c context.Context, sid, mid int64) (res []*l.ActLikeUserAchievement, err error) {
rows, err := d.db.Query(c, _userAchievementSQL, sid, mid)
if err != nil {
err = errors.Wrapf(err, "d.db.Query(%s)", _userAchievementSQL)
return
}
for rows.Next() {
n := &l.ActLikeUserAchievement{}
if err = rows.Scan(&n.ID, &n.Aid, &n.Sid, &n.Mid, &n.Award); err != nil {
err = errors.Wrapf(err, "d.db.Scan(%s)", _userAchievementSQL)
return
}
res = append(res, n)
}
if err = rows.Err(); err != nil {
err = errors.Wrapf(err, "rows.Err(%s)", _userAchievementSQL)
}
return
}
// RawActUserAchieve .
func (d *Dao) RawActUserAchieve(c context.Context, id int64) (res *l.ActLikeUserAchievement, err error) {
res = &l.ActLikeUserAchievement{}
if err = d.db.QueryRow(c, _userAchieveSQL, id).Scan(&res.ID, &res.Aid, &res.Sid, &res.Mid, &res.Award); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
err = errors.Wrapf(err, "d.db.QueryRow(%s)", _userAchieveSQL)
}
}
return
}
// ActUserAchieveChange .
func (d *Dao) ActUserAchieveChange(c context.Context, id, award int64) (upID int64, err error) {
var res sql.Result
if res, err = d.db.Exec(c, _userAchieveUpSQL, award, id); err != nil {
err = errors.Wrapf(err, "d.db.Exec(%s)", _userAchieveUpSQL)
return
}
return res.RowsAffected()
}

View File

@@ -0,0 +1,75 @@
package like
import (
"context"
l "go-common/app/interface/main/activity/model/like"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestLikeAddUserAchievment(t *testing.T) {
convey.Convey("AddUserAchievment", t, func(ctx convey.C) {
var (
c = context.Background()
userAchi = &l.ActLikeUserAchievement{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
ID, err := d.AddUserAchievment(c, userAchi)
ctx.Convey("Then err should be nil.ID should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(ID, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeUserAchievement(t *testing.T) {
convey.Convey("UserAchievement", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(0)
mid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.UserAchievement(c, sid, mid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeRawActUserAchieve(t *testing.T) {
convey.Convey("RawActUserAchieve", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.RawActUserAchieve(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestLikeActUserAchieveChange(t *testing.T) {
convey.Convey("ActUserAchieveChange", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
award = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
upID, err := d.ActUserAchieveChange(c, id, award)
ctx.Convey("Then err should be nil.upID should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(upID, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,54 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = [
"memcached.go",
"sports.go",
],
importpath = "go-common/app/interface/main/activity/dao/sports",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/activity/conf:go_default_library",
"//app/interface/main/activity/model/sports:go_default_library",
"//library/cache/memcache:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/net/metadata:go_default_library",
"//library/stat/prom:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)
go_test(
name = "go_default_test",
srcs = ["sports_test.go"],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/activity/conf:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)

View File

@@ -0,0 +1,54 @@
package sports
import (
"context"
"encoding/json"
"fmt"
"go-common/library/cache/memcache"
"go-common/library/log"
)
const (
_preQq = "q_"
)
func keyQq(tp int64) string {
return fmt.Sprintf("%s%d", _preQq, tp)
}
// QqCache get qq from cache
func (d *Dao) QqCache(c context.Context, tp int64) (rs *json.RawMessage, err error) {
var (
mckey = keyQq(tp)
conn = d.mc.Get(c)
item *memcache.Item
)
defer conn.Close()
if item, err = conn.Get(mckey); err != nil {
if err == memcache.ErrNotFound {
err = nil
} else {
log.Error("conn.Get error(%v)", err)
}
return
}
if err = conn.Scan(item, &rs); err != nil {
log.Error("item.Scan error(%v)", err)
}
return
}
// SetQqCache set qq to cache
func (d *Dao) SetQqCache(c context.Context, v *json.RawMessage, tp int64) (err error) {
var (
conn = d.mc.Get(c)
mckey = keyQq(tp)
)
defer conn.Close()
if err = conn.Set(&memcache.Item{Key: mckey, Object: v, Flags: memcache.FlagJSON, Expiration: d.mcQqExpire}); err != nil {
log.Error("conn.Set error(%v)", err)
return
}
return
}

View File

@@ -0,0 +1,127 @@
package sports
import (
"context"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"net/url"
"time"
"go-common/app/interface/main/activity/conf"
"go-common/app/interface/main/activity/model/sports"
"go-common/library/cache/memcache"
"go-common/library/ecode"
xecocde "go-common/library/ecode"
"go-common/library/log"
xhttp "go-common/library/net/http/blademaster"
"go-common/library/net/metadata"
"go-common/library/stat/prom"
)
const (
_qqAppID = "9"
_qqAppKey = "TWF0Y2hVbmlvbjpBUFBLRVk6OQ=="
_newsAppID = "openapi_for_bilibili"
_newsAppKey = "d2c0d130c49baadc3d43fc731caecd43"
)
// PromError stat and log.
func PromError(name string, format string, args ...interface{}) {
prom.BusinessErrCount.Incr(name)
log.Error(format, args...)
}
// Dao dao.
type Dao struct {
// http
httpSports *xhttp.Client
dClient *http.Client
// sports api
sportsURI, newsURI string
mc *memcache.Pool
mcQqExpire int32
}
// New dao new.
func New(c *conf.Config) (d *Dao) {
d = &Dao{
httpSports: xhttp.NewClient(c.HTTPClientSports),
dClient: http.DefaultClient,
sportsURI: c.Host.Sports,
newsURI: c.Host.QqNews,
mc: memcache.NewPool(c.Memcache.Like),
mcQqExpire: int32(time.Duration(c.Memcache.QqExpire) / time.Second),
}
return
}
// Qq get qq.
func (d *Dao) Qq(c context.Context, params url.Values, route string) (rs *json.RawMessage, err error) {
ip := metadata.String(c, metadata.RemoteIP)
var res struct {
Code int `json:"code"`
Data json.RawMessage `json:"data"`
}
params.Del("route")
params.Set("appId", _qqAppID)
params.Set("appKey", _qqAppKey)
if err = d.httpSports.Get(c, d.sportsURI+"/"+route, ip, params, &res); err != nil {
log.Error("d.httpSports.Get(%s) err(%v)", d.sportsURI+"/"+route+"?"+params.Encode(), err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("d.httpSports.Get(%s) param(%v) ecode err(%d)", d.sportsURI, params, res.Code)
err = ecode.Int(res.Code)
return
}
rs = &res.Data
return
}
// QqNews get qq news.
func (d *Dao) QqNews(c context.Context, params url.Values, route string) (rs *sports.QqRes, err error) {
var (
req *http.Request
resp *http.Response
cancel func()
)
params.Set("chlid", "news_news_football")
params.Set("appkey", _newsAppKey)
params.Set("appid", _newsAppID)
if req, err = http.NewRequest("GET", d.newsURI+"/"+route+"?"+params.Encode(), nil); err != nil {
log.Error("QqNews http.NewRequest(%s) error(%v)", d.newsURI+"/"+route+"?"+params.Encode(), err)
return
}
c, cancel = context.WithTimeout(c, time.Duration(conf.Conf.Rule.DTimeout))
defer cancel()
req = req.WithContext(c)
if resp, err = d.dClient.Do(req); err != nil {
log.Error("QqNews httpClient.Do(%s) error(%v)", d.newsURI+"/"+route+"?"+params.Encode(), err)
return
}
defer resp.Body.Close()
if resp.StatusCode >= http.StatusBadRequest {
log.Error("QqNews url(%s) resp.StatusCode error(%v)", d.newsURI+"/"+route+"?"+params.Encode(), err)
return
}
bs, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Error("QqNews ioutil.ReadAll() error(%v)", err)
return
} else if len(bs) == 0 {
return
}
if e := json.Unmarshal(bs, &rs); e != nil {
if e != io.EOF {
log.Error("json decode body(%s) error(%v)", string(bs), e)
}
}
if rs.Ret != 0 {
err = xecocde.ActivityServerTimeout
rs = nil
return
}
return
}

View File

@@ -0,0 +1,39 @@
package sports
import (
"context"
"flag"
"net/url"
"path/filepath"
"testing"
"go-common/app/interface/main/activity/conf"
. "github.com/smartystreets/goconvey/convey"
)
var d *Dao
func WithDao(f func(d *Dao)) func() {
return func() {
dir, _ := filepath.Abs("../cmd/activity-test.toml")
flag.Set("conf", dir)
conf.Init()
if d == nil {
d = New(conf.Conf)
}
f(d)
}
}
func TestDao_Qq(t *testing.T) {
Convey("test dao Qq", t, WithDao(func(d *Dao) {
var (
params url.Values
route = "matchUnion/fetchData"
)
res, err := d.Qq(context.Background(), params, route)
So(err, ShouldBeNil)
So(res, ShouldNotBeNil)
}))
}

View File

@@ -0,0 +1,65 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = [
"cache.go",
"dao.cache.go",
"dao.go",
"hbase.go",
"hbase_scan.go",
"mc.cache.go",
],
importpath = "go-common/app/interface/main/activity/dao/timemachine",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/activity/conf:go_default_library",
"//app/interface/main/activity/model/timemachine:go_default_library",
"//library/cache/memcache:go_default_library",
"//library/database/hbase.v2:go_default_library",
"//library/log:go_default_library",
"//library/stat/prom:go_default_library",
"//library/sync/pipeline/fanout:go_default_library",
"//vendor/github.com/tsuna/gohbase/hrpc:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)
go_test(
name = "go_default_test",
srcs = [
"cache_test.go",
"dao.cache_test.go",
"dao_test.go",
"hbase_test.go",
"mc.cache_test.go",
],
embed = [":go_default_library"],
tags = ["automanaged"],
deps = [
"//app/interface/main/activity/conf:go_default_library",
"//app/interface/main/activity/model/timemachine:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
"//vendor/github.com/tsuna/gohbase/hrpc:go_default_library",
],
)

View File

@@ -0,0 +1,26 @@
package timemachine
import (
"context"
"fmt"
"go-common/app/interface/main/activity/model/timemachine"
)
func timemachineKey(mid int64) string {
return fmt.Sprintf("tm_%d", mid)
}
//go:generate $GOPATH/src/go-common/app/tool/cache/gen
type _cache interface {
// cache
Timemachine(c context.Context, mid int64) (*timemachine.Item, error)
}
//go:generate $GOPATH/src/go-common/app/tool/cache/mc
type _mc interface {
// mc: -key=timemachineKey -expire=d.mcTmExpire -encode=pb
AddCacheTimemachine(c context.Context, mid int64, data *timemachine.Item) error
// mc: -key=timemachineKey
CacheTimemachine(c context.Context, mid int64) (*timemachine.Item, error)
}

View File

@@ -0,0 +1,21 @@
package timemachine
import (
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestTimemachinetimemachineKey(t *testing.T) {
convey.Convey("timemachineKey", t, func(ctx convey.C) {
var (
mid = int64(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1 := timemachineKey(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,48 @@
// Code generated by $GOPATH/src/go-common/app/tool/cache/gen. DO NOT EDIT.
/*
Package timemachine is a generated cache proxy package.
It is generated from:
type _cache interface {
// cache
Timemachine(c context.Context, mid int64) (*timemachine.Item, error)
}
*/
package timemachine
import (
"context"
"go-common/app/interface/main/activity/model/timemachine"
"go-common/library/stat/prom"
)
var _ _cache
// Timemachine get data from cache if miss will call source method, then add to cache.
func (d *Dao) Timemachine(c context.Context, id int64) (res *timemachine.Item, err error) {
addCache := true
res, err = d.CacheTimemachine(c, id)
if err != nil {
addCache = false
err = nil
}
if res != nil {
prom.CacheHit.Incr("Timemachine")
return
}
prom.CacheMiss.Incr("Timemachine")
res, err = d.RawTimemachine(c, id)
if err != nil {
return
}
miss := res
if !addCache {
return
}
d.cache.Do(c, func(c context.Context) {
d.AddCacheTimemachine(c, id, miss)
})
return
}

View File

@@ -0,0 +1,24 @@
package timemachine
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestTimemachineTimemachine(t *testing.T) {
convey.Convey("Timemachine", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.Timemachine(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
ctx.Printf("%v", res)
})
})
})
}

View File

@@ -0,0 +1,76 @@
package timemachine
import (
"time"
"go-common/app/interface/main/activity/conf"
"go-common/library/cache/memcache"
"go-common/library/sync/pipeline/fanout"
"go-common/library/database/hbase.v2"
)
// Dao .
type Dao struct {
c *conf.Config
hbase *hbase.Client
mc *memcache.Pool
cache *fanout.Fanout
//limiter *rate.Limiter
mcTmExpire int32
//tmProcStart int64
//tmProcStop int64
}
// New .
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
hbase: hbase.NewClient(c.Hbase),
mc: memcache.NewPool(c.TimeMc.Timemachine),
cache: fanout.New("timemachine", fanout.Worker(8), fanout.Buffer(10240)),
}
d.mcTmExpire = int32(time.Duration(c.TimeMc.TmExpire) / time.Second)
//d.limiter = rate.NewLimiter(1000, 100)
//go d.startTmproc(context.Background())
return d
}
// StartTmproc start time machine proc
//func (d *Dao) startTmproc(c context.Context) {
// if env.DeployEnv != env.DeployEnvPre {
// return
// }
// for {
// time.Sleep(time.Second)
// if d.tmProcStart != 0 {
// go func() {
// // scan key
// max := 10000000000
// step := max / 10000
// prefix := step - 1
// for i := 0; i < max; i += step {
// time.Sleep(10 * time.Millisecond)
// startRow := fmt.Sprintf("%0*d", 10, i)
// endRow := fmt.Sprintf("%0*d", 10, i+prefix)
// if err := d.timemachineScan(c, startRow, endRow); err != nil {
// log.Error("startTmproc timemachineScan startRow(%s) endRow(%s) error(%v)", startRow, endRow, err)
// continue
// }
// log.Info("startTmproc finish startRow(%s) endRow(%s)", startRow, endRow)
// }
// }()
// break
// }
// }
//}
// StartTmProc start time machine proc.
//func (d *Dao) StartTmProc(c context.Context) {
// atomic.StoreInt64(&d.tmProcStart, 1)
//}
// StopTmproc stop time machine proc.
//func (d *Dao) StopTmproc(c context.Context) {
// atomic.StoreInt64(&d.tmProcStop, 1)
//}

View File

@@ -0,0 +1,35 @@
package timemachine
import (
"flag"
"os"
"testing"
"go-common/app/interface/main/activity/conf"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.web-svr.activity")
flag.Set("conf_token", "22edc93e2998bf0cb0bbee661b03d41f")
flag.Set("tree_id", "2873")
flag.Set("conf_version", "docker-1")
flag.Set("deploy_env", "uat")
flag.Set("conf_host", "config.bilibili.co")
flag.Set("conf_path", "/tmp")
flag.Set("region", "sh")
flag.Set("zone", "sh001")
} else {
flag.Set("conf", "../../cmd/activity-test.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
os.Exit(m.Run())
}

View File

@@ -0,0 +1,154 @@
package timemachine
import (
"bytes"
"context"
"strconv"
"time"
"go-common/app/interface/main/activity/model/timemachine"
"go-common/library/log"
"github.com/tsuna/gohbase/hrpc"
)
const (
_hBaseUpItemTableName = "dw:mid_main_profile_y"
)
// reverse for string.
func hbaseRowKey(mid int64) string {
s := strconv.FormatInt(mid, 10)
rs := []rune(s)
l := len(rs)
for f, t := 0, l-1; f < t; f, t = f+1, t-1 {
rs[f], rs[t] = rs[t], rs[f]
}
ns := string(rs)
if l < 10 {
for i := 0; i < 10-l; i++ {
ns = ns + "0"
}
}
return ns
}
// RawTimemachine .
func (d *Dao) RawTimemachine(c context.Context, mid int64) (data *timemachine.Item, err error) {
var (
result *hrpc.Result
ctx, cancel = context.WithTimeout(c, time.Duration(d.c.Hbase.RegionReadTimeout))
key = hbaseRowKey(mid)
tableName = _hBaseUpItemTableName
)
defer cancel()
if result, err = d.hbase.GetStr(ctx, tableName, key); err != nil {
log.Error("UserItem d.hbase.GetStr tableName(%s)|mid(%d)|key(%v)|error(%v)", tableName, mid, key, err)
return
}
if result == nil {
return
}
data = &timemachine.Item{Mid: mid}
for _, c := range result.Cells {
if c == nil {
continue
}
if !bytes.Equal(c.Family, []byte("m")) {
continue
}
tmFillFields(data, c)
}
return
}
func tmFillFields(data *timemachine.Item, c *hrpc.Cell) {
var (
intVal int64
strVal string
)
strVal = string(c.Value[:])
if v, e := strconv.ParseInt(string(c.Value[:]), 10, 64); e == nil {
intVal = v
}
switch {
case bytes.Equal(c.Qualifier, []byte("is_up")):
data.IsUp = intVal
case bytes.Equal(c.Qualifier, []byte("dh")):
data.DurationHour = intVal
case bytes.Equal(c.Qualifier, []byte("adh")):
data.AvDurationHour = intVal
case bytes.Equal(c.Qualifier, []byte("a_vv")):
data.ArchiveVv = intVal
case bytes.Equal(c.Qualifier, []byte("tag_id")):
data.LikeTagID = intVal
case bytes.Equal(c.Qualifier, []byte("ls_vv")):
data.LikeSubtidVv = intVal
case bytes.Equal(c.Qualifier, []byte("ugc_avs")):
data.LikesUgc3Avids = strVal
case bytes.Equal(c.Qualifier, []byte("pgc_avs")):
data.LikePgc3Avids = strVal
case bytes.Equal(c.Qualifier, []byte("up")):
data.LikeBestUpID = intVal
case bytes.Equal(c.Qualifier, []byte("up_ad")):
data.LikeUpAvDuration = intVal
case bytes.Equal(c.Qualifier, []byte("up_ld")):
data.LikeUpLiveDuration = intVal
case bytes.Equal(c.Qualifier, []byte("up_avs")):
data.LikeUp3Avs = strVal
case bytes.Equal(c.Qualifier, []byte("up_st")):
data.LikeLiveUpSubTname = strVal
case bytes.Equal(c.Qualifier, []byte("cir_tm")):
data.BrainwashCirTime = strVal
case bytes.Equal(c.Qualifier, []byte("cir_av")):
data.BrainwashCirAvid = intVal
case bytes.Equal(c.Qualifier, []byte("cir_v")):
data.BrainwashCirVv = intVal
case bytes.Equal(c.Qualifier, []byte("fs_av")):
data.FirstSubmitAvid = intVal
case bytes.Equal(c.Qualifier, []byte("fs_tm")):
data.FirstSubmitTime = strVal
case bytes.Equal(c.Qualifier, []byte("fs_ty")):
data.FirstSubmitType = intVal
case bytes.Equal(c.Qualifier, []byte("s_av_rd")):
data.SubmitAvsRds = strVal
case bytes.Equal(c.Qualifier, []byte("bt_av")):
data.BestAvid = intVal
case bytes.Equal(c.Qualifier, []byte("bt_ty")):
data.BestAvidType = intVal
case bytes.Equal(c.Qualifier, []byte("bt_av_o")):
data.BestAvidOld = intVal
case bytes.Equal(c.Qualifier, []byte("bt_av_ty")):
data.BestAvidOldType = intVal
case bytes.Equal(c.Qualifier, []byte("o_vv")):
data.OldAvVv = intVal
case bytes.Equal(c.Qualifier, []byte("all_vv")):
data.AllVv = intVal
case bytes.Equal(c.Qualifier, []byte("live_d")):
data.UpLiveDuration = intVal
case bytes.Equal(c.Qualifier, []byte("is_live")):
data.IsLiveUp = intVal
case bytes.Equal(c.Qualifier, []byte("ld")):
data.ValidLiveDays = intVal
case bytes.Equal(c.Qualifier, []byte("md")):
data.MaxCdnNumDate = strVal
case bytes.Equal(c.Qualifier, []byte("mc")):
data.MaxCdnNum = intVal
case bytes.Equal(c.Qualifier, []byte("att")):
data.Attentions = intVal
case bytes.Equal(c.Qualifier, []byte("fan_vv")):
data.UpBestFanVv = strVal
case bytes.Equal(c.Qualifier, []byte("fan_live")):
data.UpBestFanLiveMinute = strVal
case bytes.Equal(c.Qualifier, []byte("like_tid")):
data.Like2Tids = strVal
case bytes.Equal(c.Qualifier, []byte("like_st")):
data.Like2SubTids = strVal
case bytes.Equal(c.Qualifier, []byte("wr")):
data.WinRatio = strVal
case bytes.Equal(c.Qualifier, []byte("pd_hr")):
data.PlayDurationHourRep = intVal
case bytes.Equal(c.Qualifier, []byte("lu_adr")):
data.LikeUpAvDurationRep = intVal
}
}

View File

@@ -0,0 +1,60 @@
package timemachine
//import (
// "bytes"
// "context"
// "go-common/app/interface/main/activity/model/timemachine"
// "go-common/library/log"
// "io"
//
// "github.com/tsuna/gohbase/hrpc"
//)
//
//func (d *Dao) timemachineScan(c context.Context, startRow, endRow string) (err error) {
// var scanner hrpc.Scanner
// if scanner, err = d.hbase.ScanRangeStr(c, _hBaseUpItemTableName, startRow, endRow); err != nil {
// log.Error("TimemachineScan d.hbase.Scan(%s) error(%v)", _hBaseUpItemTableName, err)
// return
// }
// for {
// if d.tmProcStop != 0 {
// err = scanner.Close()
// return
// }
// if result, e := scanner.Next(); e != nil {
// if e == io.EOF {
// return
// }
// log.Error("TimemachineScan scanner.Next error(%v)", e)
// continue
// } else {
// if result == nil {
// continue
// }
// item := &timemachine.Item{}
// for _, c := range result.Cells {
// if c == nil {
// continue
// }
// if !bytes.Equal(c.Family, []byte("m")) {
// continue
// }
// tmFillFields(item, c)
// }
// if item.Mid > 0 {
// for {
// if e := d.cache.Do(c, func(ctx context.Context) {
// if e := d.AddCacheTimemachine(ctx, item.Mid, item); e != nil {
// log.Error("timemachineScand.AddCacheTimemachine(%d) error(%v)", item.Mid, e)
// }
// }); e != nil {
// log.Warn("timemachineScan d.AddCacheTimemachine channel full(%v)", e)
// d.limiter.Wait(context.Background())
// } else {
// break
// }
// }
// }
// }
// }
//}

View File

@@ -0,0 +1,131 @@
package timemachine
import (
"context"
"testing"
"go-common/app/interface/main/activity/model/timemachine"
"github.com/smartystreets/goconvey/convey"
"github.com/tsuna/gohbase/hrpc"
)
func TestTimemachinehbaseRowKey(t *testing.T) {
convey.Convey("hbaseRowKey", t, func(ctx convey.C) {
var (
mid = int64(121212)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1 := hbaseRowKey(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestTimemachineRawTimemachine(t *testing.T) {
convey.Convey("RawTimemachine", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
data, err := d.RawTimemachine(c, mid)
ctx.Convey("Then err should be nil.data should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
ctx.Printf("%+v", data)
})
})
})
}
func TestTimemachinetmFillFields(t *testing.T) {
convey.Convey("tmFillFields", t, func(ctx convey.C) {
var (
data = &timemachine.Item{}
c = &hrpc.Cell{Qualifier: []byte("is_up"), Value: []byte("1")}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("is_up"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("dh"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("adh"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("a_vv"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("tag_id"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("ls_vv"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("ugc_avs"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("pgc_avs"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("up"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("up_ad"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("up_ld"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("up_avs"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("up_st"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("cir_tm"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("cir_av"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("cir_v"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("fs_av"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("fs_tm"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("fs_ty"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("s_av_rd"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("bt_av"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("bt_ty"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("bt_av_o"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("bt_av_ty"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("o_vv"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("all_vv"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("live_d"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("is_live"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("ld"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("md"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("mc"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("att"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("fan_vv"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("fan_live"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("like_tid"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("like_st"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("wr"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("pd_hr"), Value: []byte("1")}
tmFillFields(data, c)
c = &hrpc.Cell{Qualifier: []byte("lu_adr"), Value: []byte("1")}
tmFillFields(data, c)
})
})
}

View File

@@ -0,0 +1,68 @@
// Code generated by $GOPATH/src/go-common/app/tool/cache/mc. DO NOT EDIT.
/*
Package timemachine is a generated mc cache package.
It is generated from:
type _mc interface {
// mc: -key=timemachineKey -expire=d.mcTmExpire -encode=pb
AddCacheTimemachine(c context.Context, mid int64, data *timemachine.Item) error
// mc: -key=timemachineKey
CacheTimemachine(c context.Context, mid int64) (*timemachine.Item, error)
}
*/
package timemachine
import (
"context"
"fmt"
"go-common/app/interface/main/activity/model/timemachine"
"go-common/library/cache/memcache"
"go-common/library/log"
"go-common/library/stat/prom"
)
var _ _mc
// AddCacheTimemachine Set data to mc
func (d *Dao) AddCacheTimemachine(c context.Context, id int64, val *timemachine.Item) (err error) {
if val == nil {
return
}
conn := d.mc.Get(c)
defer conn.Close()
key := timemachineKey(id)
item := &memcache.Item{Key: key, Object: val, Expiration: d.mcTmExpire, Flags: memcache.FlagProtobuf}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheTimemachine")
log.Errorv(c, log.KV("AddCacheTimemachine", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// CacheTimemachine get data from mc
func (d *Dao) CacheTimemachine(c context.Context, id int64) (res *timemachine.Item, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := timemachineKey(id)
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheTimemachine")
log.Errorv(c, log.KV("CacheTimemachine", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = &timemachine.Item{}
err = conn.Scan(reply, res)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheTimemachine")
log.Errorv(c, log.KV("CacheTimemachine", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}

View File

@@ -0,0 +1,41 @@
package timemachine
import (
"context"
"go-common/app/interface/main/activity/model/timemachine"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestTimemachineAddCacheTimemachine(t *testing.T) {
convey.Convey("AddCacheTimemachine", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
val = &timemachine.Item{}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.AddCacheTimemachine(c, id, val)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestTimemachineCacheTimemachine(t *testing.T) {
convey.Convey("CacheTimemachine", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.CacheTimemachine(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,56 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"act.go",
"bnj.go",
"bws.go",
"http.go",
"kfc.go",
"like.go",
"match.go",
"sports.go",
"timemachine.go",
],
importpath = "go-common/app/interface/main/activity/http",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/activity/conf:go_default_library",
"//app/interface/main/activity/model/bws:go_default_library",
"//app/interface/main/activity/model/like:go_default_library",
"//app/interface/main/activity/model/sports:go_default_library",
"//app/interface/main/activity/service/bnj:go_default_library",
"//app/interface/main/activity/service/bws:go_default_library",
"//app/interface/main/activity/service/kfc:go_default_library",
"//app/interface/main/activity/service/like:go_default_library",
"//app/interface/main/activity/service/sports:go_default_library",
"//app/interface/main/activity/service/timemachine:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/net/http/blademaster/middleware/auth:go_default_library",
"//library/net/http/blademaster/middleware/verify:go_default_library",
"//library/net/metadata:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

Some files were not shown because too many files have changed in this diff Show More