newestBidding.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. package model
  2. import (
  3. "app.yhyue.com/moapp/jybase/redis"
  4. "encoding/json"
  5. "fmt"
  6. "jyBXBase/rpc/bxbase"
  7. IC "jyBXBase/rpc/init"
  8. "jyBXBase/rpc/internal/config"
  9. "log"
  10. "sort"
  11. "strings"
  12. "time"
  13. MC "app.yhyue.com/moapp/jybase/common"
  14. ME "app.yhyue.com/moapp/jybase/encrypt"
  15. elastic "app.yhyue.com/moapp/jybase/es"
  16. "app.yhyue.com/moapp/jybase/mongodb"
  17. "app.yhyue.com/moapp/jybase/mysql"
  18. "github.com/zeromicro/go-zero/core/logx"
  19. "go.mongodb.org/mongo-driver/bson/primitive"
  20. )
  21. const (
  22. search_index = "bidding"
  23. search_type = "bidding"
  24. mongodb_fields = `{"_id":1,"area":1,"publishtime":1,"s_subscopeclass":1,"subtype":1,"title":1,"toptype":1,"type":1, "buyerclass":1,"budget":1,"bidamount":1,"s_winner":1,"bidopentime":1,"buyer":1,"projectname":1,"spidercode":1,"site":1}`
  25. query = `{"query":{"terms":{"_id":["%s"]}},"_source":["_id","area", "publishtime", "s_subscopeclass", "subtype", "title", "toptype", "type", "buyerclass","bidamount","budget","projectname","buyer","bidopentime","s_winner","filetext","spidercode","site"],"from":0,"size":%d}`
  26. multi_match = `{"multi_match": {"query": %s,"type": "phrase", "fields": ["title"]}}`
  27. query_bool_must = `{"terms":{"%s":[%s]}}`
  28. query_bool_must_and = `{"bool":{"must":[%s],"must_not":[%s]}}`
  29. search_field = `"_id","area", "publishtime", "s_subscopeclass", "subtype", "title", "toptype", "type", "buyerclass","bidamount","budget","projectname","buyer","bidopentime","s_winner","filetext","isValidFile","spidercode","site"`
  30. query_city_hkeys = `{"query":{"bool":{"must":[%s],"should":[%s],"minimum_should_match":%d}},"highlight": {"pre_tags": ["<a>"],"post_tags": ["</a>"],"fields": {"title": {"fragment_size": 0,"number_of_fragments": 1}}},"_source":[` + search_field + `],"sort":[{"publishtime":"desc"},{"budget":"desc"}],"from":0,"size":%d}`
  31. Pushbidding = "global_common_data.dws_f_bid_baseinfo"
  32. Province = "province"
  33. StatusCache = iota // 0 -不存缓存 本来查的就是缓存的数据
  34. StatusNoLogin // 1-未登录用户
  35. StatusLoginUser // 2-用户自己的key
  36. StatusLogin // 3-登录用户最新标讯
  37. )
  38. type NewestInfo struct {
  39. TableName string
  40. UserId string
  41. MysqlDb *mysql.Mysql
  42. NewUserId int64
  43. PushMysql *mysql.Mysql
  44. NewsLimitNum int64 // 最新标讯数量条数限制
  45. IsEnt bool
  46. }
  47. var mysqlTables = map[string]string{
  48. "f": "push.pushsubscribe",
  49. "v": "push.pushsubscribe",
  50. "m": "push.pushmember",
  51. "e": "push.pushentniche",
  52. }
  53. func GetRoleNewestInfoService(AppId, MgoUserId string, NewUserId, AccountId, EntId, EntUserId, PositionType, PositionId int64) (roleNewestInfo *NewestInfo, flag string) {
  54. powerCheck := IC.Middleground.PowerCheckCenter.Check(AppId, MgoUserId, NewUserId, AccountId, EntId, PositionType, PositionId)
  55. thisUserId := MC.If(PositionType == 1, MC.InterfaceToStr(EntUserId), MC.InterfaceToStr(NewUserId)).(string)
  56. thisNewUserId := MC.If(PositionType == 1, EntUserId, NewUserId).(int64)
  57. if powerCheck.Member.Status > 0 {
  58. // 大会员
  59. flag = "m"
  60. } else if powerCheck.Entniche.Status > 0 && powerCheck.Entniche.PowerSource != 1 && powerCheck.Entniche.IsEntPower == 1 {
  61. // 商机管理
  62. flag = "e"
  63. } else if powerCheck.Vip.Status > 0 {
  64. // 超级订阅
  65. flag = "v"
  66. } else {
  67. // 普通用户
  68. flag = "f"
  69. }
  70. thisUserType := MC.If(PositionType == 1, "e", flag).(string)
  71. return GetNewestInfo(thisUserId, thisUserType, thisNewUserId), flag
  72. }
  73. func GetNewestInfo(userId, userType string, newUserId int64) *NewestInfo {
  74. nt := &NewestInfo{
  75. UserId: userId,
  76. TableName: mysqlTables[userType],
  77. MysqlDb: IC.BaseServiceMysql,
  78. NewUserId: newUserId,
  79. NewsLimitNum: IC.C.NewsLimitNum,
  80. }
  81. return nt
  82. }
  83. // GetPushHistoryCount 缓存code 配置最新的redis code;可以感觉redis内存大小 调节redis存储;
  84. // 根据GetPushHistoryCount 返回值 作为列表缓存key中一个参数
  85. func (n *NewestInfo) GetPushHistoryCount() int64 {
  86. countKey := fmt.Sprintf(IC.C.NewsCache.Count.Key, n.TableName, n.UserId)
  87. if b := redis.GetInt("new", countKey); b != 0 {
  88. return int64(b)
  89. }
  90. countSql := "SELECT COUNT(1) FROM (SELECT 1 FROM %s WHERE userid = %d LIMIT 1) AS ph"
  91. //countSql := "select count(1) from %s a where a.userid=%d order by a.id desc"
  92. countSql = fmt.Sprintf(countSql, n.TableName, n.NewUserId)
  93. timeOut := IC.C.NewsCache.Count.Timeout
  94. c := n.MysqlDb.CountBySql(countSql)
  95. if c > 0 {
  96. timeOut = timeOut * 7
  97. } else {
  98. c = -1
  99. }
  100. redis.Put("new", countKey, c, timeOut) //过期时间走配置,比最新标讯列表缓存时间 要短1/10 尽量不超过两分钟
  101. return c
  102. }
  103. // 判断当前用户是否有最新推送信息
  104. func (n *NewestInfo) IsHasNewPushData(time int64) bool {
  105. return n.MysqlDb.CountBySql(fmt.Sprintf("SELECT COUNT(1) FROM (SELECT 1 FROM %s WHERE userid = %d AND date > %d LIMIT 1) AS ph", n.TableName, n.NewUserId, time)) > 0
  106. }
  107. // GetPushHistory
  108. func (n *NewestInfo) GetPushHistory() (res []*bxbase.NewestList) {
  109. //
  110. findSQL := "select a.infoid,REPLACE(a.matchkeys,'+',' ') as matchkeys,a.attachment_count,a.budget,a.bidamount from %s a where a.userid=%d order by a.id desc limit ?"
  111. findSQL = fmt.Sprintf(findSQL, n.TableName, n.NewUserId)
  112. logx.Info(n.TableName, "-------", n.NewUserId, ",findSQL:", findSQL)
  113. list := n.MysqlDb.SelectBySql(findSQL, n.NewsLimitNum)
  114. if len(*list) > 0 && list != nil {
  115. m := map[string]bool{}
  116. es_ids := []string{}
  117. infos := map[string]*bxbase.NewestList{}
  118. for _, v := range *list {
  119. infoId := MC.ObjToString(v["infoid"])
  120. if m[infoId] {
  121. continue
  122. }
  123. es_ids = append(es_ids, infoId)
  124. m[MC.ObjToString(v["infoid"])] = true
  125. //
  126. infos[infoId] = &bxbase.NewestList{
  127. Id: ME.EncodeArticleId2ByCheck(MC.ObjToString(v["infoid"])),
  128. Matchkeys: strings.Split(MC.ObjToString(v["matchkeys"]), " "),
  129. Budget: MC.Int64All(v["budget"]),
  130. Bidamount: MC.Int64All(v["bidamount"]),
  131. FileExists: MC.Int64All(v["attachment_count"]) > 0,
  132. }
  133. }
  134. if len(es_ids) > 0 {
  135. list := elastic.Get(search_index, search_type, fmt.Sprintf(query, strings.Join(es_ids, `","`), len(es_ids)))
  136. if list != nil {
  137. for _, v := range *list {
  138. _id := MC.ObjToString(v["_id"])
  139. bn := infos[_id]
  140. bn.Title = MC.ObjToString(v["title"])
  141. bn.PublishTime = MC.Int64All(v["publishtime"])
  142. bn.Subtype = MC.If(v["subtype"] != nil, MC.ObjToString(v["subtype"]), MC.ObjToString(v["toptype"])).(string)
  143. bn.Area = MC.If(MC.ObjToString(v["area"]) == "A", "全国", MC.ObjToString(v["area"])).(string)
  144. bn.Buyerclass = MC.ObjToString(v["buyerclass"])
  145. bn.City = MC.ObjToString(v["city"])
  146. bn.Industry = MC.If(MC.ObjToString(v["s_subscopeclass"]) != "", strings.Split(strings.Split(MC.ObjToString(v["s_subscopeclass"]), ",")[0], "_")[0], "").(string)
  147. bn.SpiderCode = MC.ObjToString(v["spidercode"])
  148. bn.Site = MC.ObjToString(v["site"])
  149. }
  150. }
  151. }
  152. //mongodb bidding
  153. mgo_ids := []primitive.ObjectID{}
  154. for _, v := range es_ids {
  155. if infos[v].Title == "" {
  156. mgo_ids = append(mgo_ids, mongodb.StringTOBsonId(v))
  157. }
  158. }
  159. if len(mgo_ids) > 0 {
  160. list, ok := IC.MgoBidding.Find("bidding", map[string]interface{}{"_id": map[string]interface{}{"$in": mgo_ids}}, nil, mongodb_fields, false, -1, -1)
  161. if ok && *list != nil {
  162. for _, v := range *list {
  163. _id := mongodb.BsonIdToSId(v["_id"])
  164. bn := infos[_id]
  165. bn.Title = MC.ObjToString(v["title"])
  166. bn.PublishTime = MC.Int64All(v["publishtime"])
  167. bn.Subtype = MC.If(v["subtype"] != nil, MC.ObjToString(v["subtype"]), MC.ObjToString(v["toptype"])).(string)
  168. bn.Area = MC.If(MC.ObjToString(v["area"]) == "A", "全国", MC.ObjToString(v["area"])).(string)
  169. bn.Buyerclass = MC.ObjToString(v["buyerclass"])
  170. bn.City = MC.ObjToString(v["city"])
  171. bn.Industry = MC.If(MC.ObjToString(v["s_subscopeclass"]) != "", strings.Split(strings.Split(MC.ObjToString(v["s_subscopeclass"]), ",")[0], "_")[0], "").(string)
  172. bn.SpiderCode = MC.ObjToString(v["spidercode"])
  173. bn.Site = MC.ObjToString(v["site"])
  174. }
  175. }
  176. }
  177. //mongodb bidding_back
  178. mgo_back_ids := []primitive.ObjectID{}
  179. for _, v := range mgo_ids {
  180. if infos[mongodb.BsonIdToSId(v)].Title == "" {
  181. mgo_back_ids = append(mgo_back_ids, v)
  182. }
  183. }
  184. if len(mgo_back_ids) > 0 {
  185. list, ok := IC.MgoBidding.Find("bidding_back", map[string]interface{}{"_id": map[string]interface{}{"$in": mgo_back_ids}}, nil, mongodb_fields, false, -1, -1)
  186. if ok && *list != nil {
  187. for _, v := range *list {
  188. _id := mongodb.BsonIdToSId(v["_id"])
  189. bn := infos[_id]
  190. bn.Title = MC.ObjToString(v["title"])
  191. bn.PublishTime = MC.Int64All(v["publishtime"])
  192. bn.Subtype = MC.If(v["subtype"] != nil, MC.ObjToString(v["subtype"]), MC.ObjToString(v["toptype"])).(string)
  193. bn.Area = MC.If(MC.ObjToString(v["area"]) == "A", "全国", MC.ObjToString(v["area"])).(string)
  194. bn.Buyerclass = MC.ObjToString(v["buyerclass"])
  195. bn.City = MC.ObjToString(v["city"])
  196. bn.Industry = MC.If(MC.ObjToString(v["s_subscopeclass"]) != "", strings.Split(strings.Split(MC.ObjToString(v["s_subscopeclass"]), ",")[0], "_")[0], "").(string)
  197. bn.SpiderCode = MC.ObjToString(v["spidercode"])
  198. bn.Site = MC.ObjToString(v["site"])
  199. }
  200. }
  201. }
  202. //
  203. for _, v := range infos {
  204. res = append(res, v)
  205. }
  206. }
  207. return
  208. }
  209. // 根据定位或者搜索历史 查es
  210. func NewestQuery(city, keys, subtype string) (str string) {
  211. var musts, bools []string
  212. if keys != "" {
  213. for _, v := range strings.Split(keys, ",") {
  214. keys := strings.Split(v, " ") //历史搜索 空格划分
  215. must_tmp := []string{}
  216. for _, key := range keys {
  217. must_tmp = append(must_tmp, fmt.Sprintf(multi_match, "\""+key+"\""))
  218. }
  219. bools = append(bools, fmt.Sprintf(query_bool_must_and, strings.Join(must_tmp, ","), ""))
  220. }
  221. }
  222. if city != "" {
  223. musts = append(musts, fmt.Sprintf(query_bool_must, "city", `"`+city+`"`))
  224. }
  225. //未登录首页推送数据限制
  226. if subtype != "" {
  227. musts = append(musts, fmt.Sprintf(query_bool_must, "subtype", subtype))
  228. }
  229. minimum_should_match := 0
  230. if len(bools) > 0 {
  231. minimum_should_match = 1
  232. }
  233. str = fmt.Sprintf(query_city_hkeys, strings.Join(musts, ","), strings.Join(bools, ","), minimum_should_match, IC.C.NewsLimitNum)
  234. logx.Info("str:", str)
  235. return
  236. }
  237. // es查询
  238. func NewestES(doSearchStr string) (res []*bxbase.NewestList) {
  239. list := elastic.Get(search_index, search_type, doSearchStr)
  240. if list != nil && len(*list) > 0 {
  241. for _, v := range *list {
  242. _id := mongodb.BsonIdToSId(v["_id"])
  243. isValidFile, _ := v["isValidFile"].(bool)
  244. res = append(res, &bxbase.NewestList{
  245. Id: ME.EncodeArticleId2ByCheck(_id),
  246. Title: MC.ObjToString(v["title"]),
  247. Subtype: MC.If(v["subtype"] != nil, MC.ObjToString(v["subtype"]), MC.ObjToString(v["toptype"])).(string),
  248. Area: MC.If(MC.ObjToString(v["area"]) == "A", "全国", MC.ObjToString(v["area"])).(string),
  249. Buyerclass: MC.ObjToString(v["buyerclass"]),
  250. City: MC.ObjToString(v["city"]),
  251. Industry: MC.If(MC.ObjToString(v["s_subscopeclass"]) != "", strings.Split(strings.Split(MC.ObjToString(v["s_subscopeclass"]), ",")[0], "_")[0], "").(string),
  252. Budget: MC.Int64All(v["budget"]),
  253. Bidamount: MC.Int64All(v["bidamount"]),
  254. FileExists: isValidFile, //附件
  255. PublishTime: MC.Int64All(v["publishtime"]),
  256. Site: MC.ObjToString(v["site"]),
  257. SpiderCode: MC.ObjToString(v["spidercode"]),
  258. })
  259. }
  260. }
  261. return
  262. }
  263. // GetRedisKeyTimeout 获取缓存的key 和超时时间
  264. func GetRedisKeyTimeout(status int, positionId int64) config.CacheConfig {
  265. var (
  266. redisKey, cuKey string
  267. timeOut, cuTimeOut int
  268. )
  269. switch status {
  270. case StatusNoLogin:
  271. redisKey = IC.C.NewsCache.NoLogin.Key
  272. redisKey = fmt.Sprintf(redisKey, time.Now().Year(), time.Now().Month(), time.Now().Day())
  273. timeOut = IC.C.NewsCache.NoLogin.Timeout
  274. cuKey = fmt.Sprintf("%s_%s", redisKey, IC.C.NewsCache.NoLogin.CacheUpdateKey)
  275. cuTimeOut = IC.C.NewsCache.NoLogin.CacheUpdateTimeout
  276. case StatusLoginUser:
  277. redisKey = IC.C.NewsCache.LoginUser.Key // 登录用户使用的缓存key
  278. redisKey = fmt.Sprintf(redisKey, positionId, time.Now().Year(), time.Now().Month(), time.Now().Day())
  279. timeOut = IC.C.NewsCache.LoginUser.Timeout
  280. cuKey = fmt.Sprintf("%s_%s", redisKey, IC.C.NewsCache.LoginUser.CacheUpdateKey)
  281. cuTimeOut = IC.C.NewsCache.LoginUser.CacheUpdateTimeout
  282. case StatusLogin:
  283. redisKey = IC.C.NewsCache.Login.Key // 登录用户使用的最新标讯缓存key
  284. redisKey = fmt.Sprintf(redisKey, time.Now().Year(), time.Now().Month(), time.Now().Day())
  285. timeOut = IC.C.NewsCache.Login.Timeout
  286. cuKey = fmt.Sprintf("%s_%s", redisKey, IC.C.NewsCache.Login.CacheUpdateKey)
  287. cuTimeOut = IC.C.NewsCache.Login.CacheUpdateTimeout
  288. }
  289. return config.CacheConfig{
  290. Key: redisKey,
  291. Timeout: timeOut,
  292. CacheUpdateKey: cuKey,
  293. CacheUpdateTimeout: cuTimeOut,
  294. }
  295. }
  296. // PutNewsCache 存缓存
  297. func PutNewsCache(redisKey string, redisTimeout int, list []*bxbase.NewestList) {
  298. b, err := json.Marshal(list)
  299. if err != nil {
  300. log.Printf("保存缓存 序列化异常,data:%s,err:%s\n", list, err.Error())
  301. return
  302. }
  303. if err = redis.PutBytes("new", redisKey, &b, redisTimeout); err != nil {
  304. log.Printf("保存缓存 redis 异常,key:%s,err:%s\n", redisKey, err.Error())
  305. }
  306. }
  307. // GetNewsCache 取缓存
  308. func GetNewsCache(cc config.CacheConfig) (list []*bxbase.NewestList, err error) {
  309. redisByte, err := redis.GetBytes("new", cc.Key)
  310. if err != nil || redisByte == nil || len(*redisByte) == 0 {
  311. return list, err
  312. }
  313. err = json.Unmarshal(*redisByte, &list)
  314. if err != nil {
  315. logx.Info(fmt.Sprintf("读取缓存 序列化异常,err:%s", err.Error()))
  316. return nil, err
  317. }
  318. return list, nil
  319. }
  320. type NewSet struct {
  321. Status int
  322. RedisKeyModel config.CacheConfig
  323. RedisStatus int
  324. Query string
  325. }
  326. // 排序 入缓存
  327. // status : 0 -拿到的是缓存 不用再处理也不用存缓存 1-存到未登录用户 2-存到用户自己的key 3-存到登录用户最新标讯
  328. func DataSortInRedis(r *bxbase.NewsetBiddingResp, status int, positionId int64) {
  329. //排序
  330. sort.Slice(r.Data.List, func(i, j int) bool {
  331. return r.Data.List[i].PublishTime > r.Data.List[j].PublishTime
  332. })
  333. redisKeyModel := GetRedisKeyTimeout(status, positionId)
  334. go PutNewsCache(redisKeyModel.Key, redisKeyModel.Timeout, r.Data.List)
  335. }
  336. // 延长缓存
  337. // 获取最新数据 -- 延长缓存时间7天---待调整: 1、判断是否需要更新;2、判断订阅信息是否存在,如果存在是否是最新推送,3、订阅信息查推送缓存(只有个人版有缓存:pushcache_2_a )
  338. func ExtendNewListCache(n *NewSet, in *bxbase.NewestBiddingReq, list []*bxbase.NewestList) {
  339. if n.RedisKeyModel.Key != "" {
  340. now := time.Now()
  341. if n.RedisKeyModel.CacheUpdateKey != "" {
  342. var (
  343. res = &bxbase.NewsetBiddingResp{
  344. Data: &bxbase.NewsetBidding{
  345. List: []*bxbase.NewestList{},
  346. },
  347. }
  348. updateTime = redis.GetInt("new", n.RedisKeyModel.CacheUpdateKey)
  349. )
  350. switch n.RedisStatus {
  351. case StatusLoginUser:
  352. //十五分钟内 更新过一次 不再更新
  353. if int(now.Unix())-updateTime > n.RedisKeyModel.CacheUpdateTimeout {
  354. // 登录用户
  355. roleNewestInfo, _ := GetRoleNewestInfoService(in.AppId, in.MgoUserId, in.NewUserId, in.AccountId, in.EntId, in.EntUserId, in.PositionType, in.PositionId)
  356. //当前用户有最新推送信息
  357. lastPublishTime := list[len(list)-1].PublishTime
  358. if roleNewestInfo.IsHasNewPushData(lastPublishTime) {
  359. // 查推送
  360. subscribeTime := time.Now()
  361. res.Data.List = roleNewestInfo.GetPushHistory()
  362. log.Println(in.PositionId, "获取订阅数据 存缓存 耗时:", time.Since(subscribeTime).Seconds())
  363. } else {
  364. res.Data.List = list
  365. }
  366. }
  367. default:
  368. //十五分钟内 更新过一次 不再更新
  369. if int(now.Unix())-updateTime > n.RedisKeyModel.CacheUpdateTimeout {
  370. res.Data.List = NewestES(n.Query)
  371. }
  372. }
  373. if len(res.Data.List) > 0 {
  374. //更新update time
  375. redis.Put("new", n.RedisKeyModel.CacheUpdateKey, now.Unix(), n.RedisKeyModel.CacheUpdateTimeout)
  376. go DataSortInRedis(res, n.RedisStatus, in.PositionId)
  377. }
  378. }
  379. ////剩余时间 在 IC.C.NewsTimeOut 之内
  380. //if ttl := redis.GetTTL("new", n.RedisKeyModel.Key); ttl-IC.C.NewsTimeOut < 0 {
  381. //
  382. //}
  383. }
  384. }