Create & Init Project...

This commit is contained in:
2019-04-22 18:49:16 +08:00
commit fc4fa37393
25440 changed files with 4054998 additions and 0 deletions

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)
})
})
})
}