main.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. package main
  2. import (
  3. util "app.yhyue.com/data_processing/common_utils"
  4. "app.yhyue.com/data_processing/common_utils/elastic"
  5. "app.yhyue.com/data_processing/common_utils/log"
  6. "app.yhyue.com/data_processing/common_utils/mongodb"
  7. "app.yhyue.com/data_processing/common_utils/redis"
  8. "app.yhyue.com/data_processing/common_utils/udp"
  9. "encoding/json"
  10. "fmt"
  11. "github.com/robfig/cron"
  12. "github.com/spf13/cobra"
  13. "go.mongodb.org/mongo-driver/bson"
  14. "go.uber.org/zap"
  15. "net"
  16. "os"
  17. "proposed_project/config"
  18. "sync"
  19. "time"
  20. )
  21. var (
  22. UdpClient udp.UdpClient
  23. Es *elastic.Elastic
  24. EsBulkSize = 200
  25. saveEsPool = make(chan map[string]interface{}, 5000)
  26. saveEsSp = make(chan bool, 3)
  27. )
  28. func main() {
  29. rootCmd := &cobra.Command{Use: "my cmd"}
  30. rootCmd.AddCommand(tags())
  31. rootCmd.AddCommand(project())
  32. rootCmd.AddCommand(nzjData())
  33. rootCmd.AddCommand(projectAdd())
  34. rootCmd.AddCommand(tidbSave())
  35. rootCmd.AddCommand(tidbAddSave())
  36. rootCmd.AddCommand(redisSave())
  37. rootCmd.AddCommand(esSave())
  38. rootCmd.AddCommand(projectComb())
  39. rootCmd.AddCommand(projectCombTidb())
  40. rootCmd.AddCommand(projectCombAdd())
  41. if err := rootCmd.Execute(); err != nil {
  42. fmt.Println("rootCmd.Execute failed", err.Error())
  43. }
  44. }
  45. func tags() *cobra.Command {
  46. cmdClient := &cobra.Command{
  47. Use: "tags",
  48. Short: "Start processing tags data",
  49. Run: func(cmd *cobra.Command, args []string) {
  50. InitRule()
  51. go UpdateMethod()
  52. taskRun()
  53. c := make(chan bool, 1)
  54. <-c
  55. },
  56. }
  57. return cmdClient
  58. }
  59. func project() *cobra.Command {
  60. cmdClient := &cobra.Command{
  61. Use: "project",
  62. Short: "Start processing project data",
  63. Run: func(cmd *cobra.Command, args []string) {
  64. InitRule()
  65. loadProject()
  66. go updateAllQueue()
  67. UdpClient = udp.UdpClient{Local: config.Conf.Udp.LocPort, BufSize: 1024}
  68. UdpClient.Listen(processUdpMsg)
  69. log.Info("Udp服务监听", zap.String("port:", config.Conf.Udp.LocPort))
  70. c := make(chan bool, 1)
  71. <-c
  72. },
  73. }
  74. return cmdClient
  75. }
  76. func nzjData() *cobra.Command {
  77. cmdClient := &cobra.Command{
  78. Use: "nzj-data",
  79. Short: "Start processing project data",
  80. Run: func(cmd *cobra.Command, args []string) {
  81. if LastId == "" {
  82. _ = cmd.Help()
  83. os.Exit(0)
  84. }
  85. go saveMethod()
  86. sid, eid := taskQ()
  87. if sid != "" && eid != "" {
  88. doTask1(sid, eid)
  89. LastId = eid
  90. }
  91. crn := cron.New()
  92. cronstr := "0 */10 * * * ?" // 每10min执行一次
  93. _ = crn.AddFunc(cronstr, func() {
  94. if TaskSingle {
  95. sid, eid := taskQ()
  96. if sid != "" && eid != "" {
  97. TaskSingle = false
  98. doTask1(sid, eid)
  99. LastId = eid
  100. }
  101. } else {
  102. log.Info("上次任务未执行完成")
  103. }
  104. })
  105. crn.Start()
  106. c := make(chan bool, 1)
  107. <-c
  108. },
  109. }
  110. cmdClient.Flags().StringVarP(&LastId, "lastid", "s", "", "data start id")
  111. return cmdClient
  112. }
  113. func projectAdd() *cobra.Command {
  114. cmdClient := &cobra.Command{
  115. Use: "project-add",
  116. Short: "Start processing project data",
  117. Run: func(cmd *cobra.Command, args []string) {
  118. if LastId == "" {
  119. _ = cmd.Help()
  120. os.Exit(0)
  121. }
  122. InitRule()
  123. loadProject()
  124. go updateAllQueue()
  125. info, _ := MgoBid.Find("nzj_bidding", nil, `{"_id": -1}`, nil, true, -1, 1)
  126. doTask(LastId, mongodb.BsonIdToSId((*info)[0]["_id"]))
  127. LastId = mongodb.BsonIdToSId((*info)[0]["_id"])
  128. crn := cron.New()
  129. cronstr := "0 */30 * * * ?" // 每30min执行一次
  130. _ = crn.AddFunc(cronstr, func() {
  131. if TaskSingle {
  132. info, _ := MgoBid.Find("nzj_bidding", nil, `{"_id": -1}`, nil, true, -1, 1)
  133. TaskSingle = false
  134. doTask(LastId, mongodb.BsonIdToSId((*info)[0]["_id"]))
  135. LastId = mongodb.BsonIdToSId((*info)[0]["_id"])
  136. } else {
  137. log.Info("上次任务未执行完成")
  138. }
  139. })
  140. crn.Start()
  141. c := make(chan bool, 1)
  142. <-c
  143. },
  144. }
  145. cmdClient.Flags().StringVarP(&LastId, "lastid", "s", "", "data start id")
  146. return cmdClient
  147. }
  148. func tidbSave() *cobra.Command {
  149. cmdClient := &cobra.Command{
  150. Use: "tidb",
  151. Short: "Start processing project save to tidb",
  152. Run: func(cmd *cobra.Command, args []string) {
  153. InitMysql()
  154. InitArea()
  155. go SaveFunc("dwd_f_nzj_baseinfo_new", BaseField)
  156. go SaveRFunc("dwd_f_nzj_follw_record_new", RecordField)
  157. go SaveCFunc("dwd_f_nzj_contact_new", ContactField)
  158. go SaveCyFunc("dwd_f_nzj_category_tags_new", CategoryField)
  159. go SaveEntFunc("dwd_f_nzj_ent_new", EntField)
  160. redis.InitRedis1("ent_id=172.17.4.189:8379", 6) // name_id
  161. taskTidb(nil)
  162. c := make(chan bool, 1)
  163. <-c
  164. },
  165. }
  166. return cmdClient
  167. }
  168. func tidbAddSave() *cobra.Command {
  169. cmdClient := &cobra.Command{
  170. Use: "tidb-add",
  171. Short: "Start processing project save to tidb",
  172. Run: func(cmd *cobra.Command, args []string) {
  173. InitMysql()
  174. InitArea()
  175. //go SaveFunc("dwd_f_nzj_baseinfo", BaseField)
  176. //go SaveRFunc("dwd_f_nzj_follw_record", RecordField)
  177. //go SaveCFunc("dwd_f_nzj_contact", ContactField)
  178. //go SaveCyFunc("dwd_f_nzj_category_tags", CategoryField)
  179. redis.InitRedis1("ent_id=172.17.4.189:8379", 6) // name_id
  180. taskTidb_add(bson.M{"pici": bson.M{"$gt": pici}})
  181. crn := cron.New()
  182. cronstr := "0 */30 * * * ?" // 每30min执行一次
  183. _ = crn.AddFunc(cronstr, func() {
  184. if TaskSingle {
  185. TaskSingle = false
  186. taskTidb_add(bson.M{"pici": bson.M{"$gt": pici}})
  187. } else {
  188. log.Info("上次任务未执行完成")
  189. }
  190. })
  191. crn.Start()
  192. c := make(chan bool, 1)
  193. <-c
  194. },
  195. }
  196. cmdClient.Flags().Int64VarP(&pici, "pici", "c", 0, "pici time")
  197. return cmdClient
  198. }
  199. func redisSave() *cobra.Command {
  200. cmdClient := &cobra.Command{
  201. Use: "redis",
  202. Short: "Start processing project save to tidb",
  203. Run: func(cmd *cobra.Command, args []string) {
  204. InitMysql()
  205. redis.InitRedis1("ent_id=172.17.4.189:8379", 6) // name_id
  206. redisDisp()
  207. },
  208. }
  209. return cmdClient
  210. }
  211. func esSave() *cobra.Command {
  212. cmdClient := &cobra.Command{
  213. Use: "es-save",
  214. Short: "Start processing project save to es",
  215. Run: func(cmd *cobra.Command, args []string) {
  216. InitMysql()
  217. InitArea()
  218. InitTagCode()
  219. InitEs()
  220. go SaveEs()
  221. esDisp()
  222. crn := cron.New()
  223. cronstr := "0 */30 * * * ?" // 每30min执行一次
  224. _ = crn.AddFunc(cronstr, func() {
  225. if TaskSingle {
  226. TaskSingle = false
  227. esDisp()
  228. } else {
  229. log.Info("上次任务未执行完成")
  230. }
  231. })
  232. crn.Start()
  233. c := make(chan bool, 1)
  234. <-c
  235. },
  236. }
  237. cmdClient.Flags().Int64VarP(&pici, "pici", "c", 0, "pici time")
  238. return cmdClient
  239. }
  240. // @Description 拟在建项目关联
  241. // @Author J 2023/4/17 09:05
  242. func projectComb() *cobra.Command {
  243. cmdClient := &cobra.Command{
  244. Use: "project-comb",
  245. Short: "Start processing combined project",
  246. Run: func(cmd *cobra.Command, args []string) {
  247. initSeg()
  248. InitEs()
  249. redis.InitRedis1(fmt.Sprintf("%s=%s", config.Conf.DB.Redis.Project, config.Conf.DB.Redis.Addr), config.Conf.DB.Redis.Dbt)
  250. redis.InitRedis1(fmt.Sprintf("%s=%s", config.Conf.DB.Redis.Proposed, config.Conf.DB.Redis.Addr), config.Conf.DB.Redis.Dbd)
  251. go SavePpMethod()
  252. taskComb()
  253. c := make(chan bool, 1)
  254. <-c
  255. },
  256. }
  257. return cmdClient
  258. }
  259. // @Description 拟在建项目关联后入tidb处理
  260. // @Author J 2023/4/17 09:06
  261. func projectCombTidb() *cobra.Command {
  262. cmdClient := &cobra.Command{
  263. Use: "project-comb-tidb",
  264. Short: "Start processing combined project",
  265. Run: func(cmd *cobra.Command, args []string) {
  266. InitMysql()
  267. initStage()
  268. redis.InitRedis1("ent_id=172.17.4.189:8379", 6) // name_id
  269. redis.InitRedis1(fmt.Sprintf("%s=%s", config.Conf.DB.Redis.Project, config.Conf.DB.Redis.Addr), config.Conf.DB.Redis.Dbt)
  270. redis.InitRedis1(fmt.Sprintf("%s=%s", config.Conf.DB.Redis.Proposed, config.Conf.DB.Redis.Addr), config.Conf.DB.Redis.Dbd)
  271. go SaveEntFunc1("dwd_f_nzj_ent", EntField)
  272. taskD()
  273. c := make(chan bool, 1)
  274. <-c
  275. },
  276. }
  277. return cmdClient
  278. }
  279. // @Description 拟在建关联数据 增量数据处理
  280. // @Author J 2023/4/24 13:51
  281. func projectCombAdd() *cobra.Command {
  282. cmdClient := &cobra.Command{
  283. Use: "project-comb-add",
  284. Short: "Start processing combined project add",
  285. Run: func(cmd *cobra.Command, args []string) {
  286. initSeg()
  287. InitEs()
  288. InitMysql()
  289. initStage()
  290. redis.InitRedis1("ent_id=172.17.4.189:8379", 6) // name_id
  291. redis.InitRedis1(fmt.Sprintf("%s=%s", config.Conf.DB.Redis.Project, config.Conf.DB.Redis.Addr), config.Conf.DB.Redis.Dbt)
  292. redis.InitRedis1(fmt.Sprintf("%s=%s", config.Conf.DB.Redis.Proposed, config.Conf.DB.Redis.Addr), config.Conf.DB.Redis.Dbd)
  293. go SaveEntFunc1("dwd_f_nzj_ent", EntField)
  294. go taskAA()
  295. go taskBB()
  296. crn := cron.New()
  297. cronstr := "0 0 22 * * ?" // 每天10点执行一次
  298. _ = crn.AddFunc(cronstr, func() {
  299. if TaskSingle {
  300. go taskAA()
  301. go taskBB()
  302. } else {
  303. log.Info("上次任务未执行完成")
  304. }
  305. })
  306. crn.Start()
  307. c := make(chan bool, 1)
  308. <-c
  309. },
  310. }
  311. return cmdClient
  312. }
  313. func processUdpMsg(act byte, data []byte, ra *net.UDPAddr) {
  314. switch act {
  315. case udp.OP_TYPE_DATA:
  316. var mapInfo map[string]interface{}
  317. err := json.Unmarshal(data, &mapInfo)
  318. log.Info("processUdpMsg", zap.Any("mapInfo:", mapInfo))
  319. gtid, _ := mapInfo["gtid"].(string)
  320. lteid, _ := mapInfo["lteid"].(string)
  321. if err != nil || gtid == "" || lteid == "" {
  322. UdpClient.WriteUdp([]byte("tidb udp error"), udp.OP_NOOP, ra)
  323. } else {
  324. //udp成功回写
  325. if k := util.ObjToString(mapInfo["key"]); k != "" {
  326. UdpClient.WriteUdp([]byte(k), udp.OP_NOOP, ra)
  327. } else {
  328. k = fmt.Sprintf("%s-%s-%s", gtid, lteid, util.ObjToString(mapInfo["stype"]))
  329. UdpClient.WriteUdp([]byte(k), udp.OP_NOOP, ra)
  330. }
  331. log.Info("start merge ...")
  332. doTask(gtid, lteid)
  333. }
  334. case udp.OP_NOOP: //下个节点回应
  335. }
  336. }
  337. func taskQ() (string, string) {
  338. log.Info("taskQ", zap.String("lastid", LastId))
  339. query := bson.M{"gtid": bson.M{"$gt": LastId}}
  340. info, _ := MgoBid.Find("field_data_record", query, `{"_id": -1}`, nil, false, -1, 1)
  341. if len(*info) > 0 {
  342. newid := util.ObjToString((*info)[0]["lteid"])
  343. log.Info("taskQ", zap.String("新lastid", newid))
  344. return LastId, newid
  345. } else {
  346. log.Info("taskQ 未发现新数据")
  347. return "", ""
  348. }
  349. }
  350. func redisDisp() {
  351. pool := make(chan bool, 5) //控制线程数
  352. wg := &sync.WaitGroup{}
  353. finalId := 0
  354. lastInfo := MysqlTool1.SelectBySql(fmt.Sprintf("SELECT id FROM %s ORDER BY id DESC LIMIT 1", "dws_f_ent_baseinfo"))
  355. if len(*lastInfo) > 0 {
  356. finalId = util.IntAll((*lastInfo)[0]["id"])
  357. }
  358. util.Debug("taskIterateSql---", "finally id", finalId)
  359. lastid, count := 0, 0
  360. for {
  361. util.Debug("重新查询,lastid---", lastid)
  362. q := fmt.Sprintf("SELECT id, name, name_id, area_code, city_code FROM %s WHERE id > %d ORDER BY id ASC limit 100000", "dws_f_ent_baseinfo", lastid)
  363. rows, err := MysqlTool1.DB.Query(q)
  364. if err != nil {
  365. util.Debug("taskIterateSql---", err)
  366. }
  367. columns, err := rows.Columns()
  368. if finalId == lastid {
  369. util.Debug("----finish----------", count)
  370. break
  371. }
  372. for rows.Next() {
  373. scanArgs := make([]interface{}, len(columns))
  374. values := make([]interface{}, len(columns))
  375. ret := make(map[string]interface{})
  376. for k := range values {
  377. scanArgs[k] = &values[k]
  378. }
  379. err = rows.Scan(scanArgs...)
  380. if err != nil {
  381. util.Debug("taskIterateSql---", err)
  382. break
  383. }
  384. for i, col := range values {
  385. if v, ok := col.([]uint8); ok {
  386. ret[columns[i]] = string(v)
  387. } else {
  388. ret[columns[i]] = col
  389. }
  390. }
  391. lastid = util.IntAll(ret["id"])
  392. count++
  393. if count%20000 == 0 {
  394. util.Debug("current-------", count, lastid)
  395. }
  396. pool <- true
  397. wg.Add(1)
  398. go func(tmp map[string]interface{}) {
  399. defer func() {
  400. <-pool
  401. wg.Done()
  402. }()
  403. redis.PutCKV("ent_id", util.ObjToString(tmp["name"]),
  404. fmt.Sprintf("%s_%s_%s", util.ObjToString(tmp["name_id"]), util.ObjToString(tmp["area_code"]), util.ObjToString(tmp["city_code"])))
  405. }(ret)
  406. ret = make(map[string]interface{})
  407. }
  408. _ = rows.Close()
  409. wg.Wait()
  410. }
  411. }
  412. var EsField = []string{"_id", "projectname", "owner", "area", "city", "district", "nature_code", "ownerclass_code", "project_stage_code", "category_code", "total_investment", "lasttime", "proposed_id"}
  413. func esDisp() {
  414. sess := MgoPro.GetMgoConn()
  415. defer MgoPro.DestoryMongoConn(sess)
  416. client := Es.GetEsConn()
  417. defer Es.DestoryEsConn(client)
  418. ch := make(chan bool, config.Conf.Serve.Thread)
  419. wg := &sync.WaitGroup{}
  420. var q bson.M
  421. if pici > 0 {
  422. q = bson.M{"pici": bson.M{"$gt": pici}}
  423. }
  424. query := sess.DB(config.Conf.DB.MongoP.Dbname).C(config.Conf.DB.MongoP.ProposedColl).Find(q).Select(SelectF).Iter()
  425. count := 0
  426. for tmp := make(map[string]interface{}); query.Next(tmp); count++ {
  427. if count%200 == 0 {
  428. log.Info(fmt.Sprintf("current --- %d", count))
  429. }
  430. if t := util.Int64All(tmp["pici"]); t > pici {
  431. pici = t
  432. }
  433. ch <- true
  434. wg.Add(1)
  435. go func(tmp map[string]interface{}) {
  436. defer func() {
  437. <-ch
  438. wg.Done()
  439. }()
  440. save := make(map[string]interface{})
  441. for _, f := range EsField {
  442. if tmp[f] == nil {
  443. continue
  444. }
  445. if f == "_id" {
  446. save["proposed_id"] = mongodb.BsonIdToSId(tmp["_id"])
  447. save["_id"] = mongodb.BsonIdToSId(tmp["_id"])
  448. } else if f == "area" {
  449. save[f] = tmp[f]
  450. save["area_code"] = AreaCode[util.ObjToString(tmp["area"])]
  451. if util.ObjToString(tmp["city"]) != "" {
  452. save["area_city"] = tmp["city"]
  453. } else {
  454. save["area_city"] = tmp["area"]
  455. }
  456. } else if f == "lasttime" {
  457. save[f] = util.Int64All(tmp[f]) * 1000
  458. } else if f == "nature_code" {
  459. save[f] = tmp[f]
  460. save["nature"] = TagCode["nature"].(map[string]interface{})[util.ObjToString(tmp[f])]
  461. } else if f == "ownerclass_code" {
  462. save[f] = tmp[f]
  463. save["ownerclass"] = TagCode["owner"].(map[string]interface{})[util.ObjToString(tmp[f])]
  464. } else if f == "project_stage_code" {
  465. save[f] = tmp[f]
  466. save["project_stage"] = TagCode["project_stage"].(map[string]interface{})[util.ObjToString(tmp[f])]
  467. } else if f == "category_code" {
  468. save[f] = tmp[f]
  469. save["category"] = TagCode["category"].(map[string]interface{})[util.ObjToString(tmp[f])]
  470. } else if f == "total_investment" {
  471. text := util.ObjToString(tmp[f])
  472. c := ObjToMoney(text)
  473. c = c / 10000
  474. if c != 0 {
  475. c, _ = util.FormatFloat(c, 4)
  476. save[f] = c
  477. }
  478. } else {
  479. save[f] = tmp[f]
  480. }
  481. }
  482. saveEsPool <- save
  483. }(tmp)
  484. tmp = make(map[string]interface{})
  485. }
  486. wg.Wait()
  487. log.Info(fmt.Sprintf("over --- %d", count))
  488. TaskSingle = true
  489. }
  490. func saveMethod() {
  491. arru := make([]map[string]interface{}, saveSize)
  492. indexu := 0
  493. for {
  494. select {
  495. case v := <-savePool:
  496. arru[indexu] = v
  497. indexu++
  498. if indexu == saveSize {
  499. saveSp <- true
  500. go func(arru []map[string]interface{}) {
  501. defer func() {
  502. <-saveSp
  503. }()
  504. MgoBid.SaveBulk("nzj_bidding", arru...)
  505. }(arru)
  506. arru = make([]map[string]interface{}, saveSize)
  507. indexu = 0
  508. }
  509. case <-time.After(1000 * time.Millisecond):
  510. if indexu > 0 {
  511. saveSp <- true
  512. go func(arru []map[string]interface{}) {
  513. defer func() {
  514. <-saveSp
  515. }()
  516. MgoBid.SaveBulk("nzj_bidding", arru...)
  517. }(arru[:indexu])
  518. arru = make([]map[string]interface{}, saveSize)
  519. indexu = 0
  520. }
  521. }
  522. }
  523. }
  524. func SaveEs() {
  525. arru := make([]map[string]interface{}, EsBulkSize)
  526. indexu := 0
  527. for {
  528. select {
  529. case v := <-saveEsPool:
  530. arru[indexu] = v
  531. indexu++
  532. if indexu == EsBulkSize {
  533. saveEsSp <- true
  534. go func(arru []map[string]interface{}) {
  535. defer func() {
  536. <-saveEsSp
  537. }()
  538. Es.BulkSave(config.Conf.DB.Es.IndexP, arru)
  539. }(arru)
  540. arru = make([]map[string]interface{}, EsBulkSize)
  541. indexu = 0
  542. }
  543. case <-time.After(1000 * time.Millisecond):
  544. if indexu > 0 {
  545. saveEsSp <- true
  546. go func(arru []map[string]interface{}) {
  547. defer func() {
  548. <-saveEsSp
  549. }()
  550. Es.BulkSave(config.Conf.DB.Es.IndexP, arru)
  551. }(arru[:indexu])
  552. arru = make([]map[string]interface{}, EsBulkSize)
  553. indexu = 0
  554. }
  555. }
  556. }
  557. }