main.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  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.Pcode, config.Conf.DB.Redis.Addr), config.Conf.DB.Redis.Db)
  250. go SavePpMethod()
  251. taskC()
  252. c := make(chan bool, 1)
  253. <-c
  254. },
  255. }
  256. return cmdClient
  257. }
  258. // @Description 拟在建项目关联后入tidb处理
  259. // @Author J 2023/4/17 09:06
  260. func projectCombTidb() *cobra.Command {
  261. cmdClient := &cobra.Command{
  262. Use: "project-comb-tidb",
  263. Short: "Start processing combined project",
  264. Run: func(cmd *cobra.Command, args []string) {
  265. InitMysql()
  266. initStage()
  267. redis.InitRedis1(fmt.Sprintf("%s=%s", config.Conf.DB.Redis.Pcode, config.Conf.DB.Redis.Addr), config.Conf.DB.Redis.Db)
  268. go SaveEntFunc1("dwd_f_nzj_ent", EntField)
  269. taskD()
  270. c := make(chan bool, 1)
  271. <-c
  272. },
  273. }
  274. return cmdClient
  275. }
  276. // @Description 拟在建关联数据 增量数据处理
  277. // @Author J 2023/4/24 13:51
  278. func projectCombAdd() *cobra.Command {
  279. cmdClient := &cobra.Command{
  280. Use: "project-comb-add",
  281. Short: "Start processing combined project add",
  282. Run: func(cmd *cobra.Command, args []string) {
  283. InitMysql()
  284. initStage()
  285. redis.InitRedis1(fmt.Sprintf("%s=%s", config.Conf.DB.Redis.Pcode, config.Conf.DB.Redis.Addr), config.Conf.DB.Redis.Db)
  286. go SaveEntFunc1("dwd_f_nzj_ent", EntField)
  287. crn := cron.New()
  288. cronstr := "0 */30 * * * ?" // 每30min执行一次
  289. _ = crn.AddFunc(cronstr, func() {
  290. if TaskSingle {
  291. TaskSingle = false
  292. go taskAA()
  293. go taskBB()
  294. } else {
  295. log.Info("上次任务未执行完成")
  296. }
  297. })
  298. crn.Start()
  299. c := make(chan bool, 1)
  300. <-c
  301. },
  302. }
  303. return cmdClient
  304. }
  305. func processUdpMsg(act byte, data []byte, ra *net.UDPAddr) {
  306. switch act {
  307. case udp.OP_TYPE_DATA:
  308. var mapInfo map[string]interface{}
  309. err := json.Unmarshal(data, &mapInfo)
  310. log.Info("processUdpMsg", zap.Any("mapInfo:", mapInfo))
  311. gtid, _ := mapInfo["gtid"].(string)
  312. lteid, _ := mapInfo["lteid"].(string)
  313. if err != nil || gtid == "" || lteid == "" {
  314. UdpClient.WriteUdp([]byte("tidb udp error"), udp.OP_NOOP, ra)
  315. } else {
  316. //udp成功回写
  317. if k := util.ObjToString(mapInfo["key"]); k != "" {
  318. UdpClient.WriteUdp([]byte(k), udp.OP_NOOP, ra)
  319. } else {
  320. k = fmt.Sprintf("%s-%s-%s", gtid, lteid, util.ObjToString(mapInfo["stype"]))
  321. UdpClient.WriteUdp([]byte(k), udp.OP_NOOP, ra)
  322. }
  323. log.Info("start merge ...")
  324. doTask(gtid, lteid)
  325. }
  326. case udp.OP_NOOP: //下个节点回应
  327. }
  328. }
  329. func taskQ() (string, string) {
  330. log.Info("taskQ", zap.String("lastid", LastId))
  331. query := bson.M{"gtid": bson.M{"$gt": LastId}}
  332. info, _ := MgoBid.Find("field_data_record", query, `{"_id": -1}`, nil, false, -1, 1)
  333. if len(*info) > 0 {
  334. newid := util.ObjToString((*info)[0]["lteid"])
  335. log.Info("taskQ", zap.String("新lastid", newid))
  336. return LastId, newid
  337. } else {
  338. log.Info("taskQ 未发现新数据")
  339. return "", ""
  340. }
  341. }
  342. func redisDisp() {
  343. pool := make(chan bool, 5) //控制线程数
  344. wg := &sync.WaitGroup{}
  345. finalId := 0
  346. lastInfo := MysqlTool1.SelectBySql(fmt.Sprintf("SELECT id FROM %s ORDER BY id DESC LIMIT 1", "dws_f_ent_baseinfo"))
  347. if len(*lastInfo) > 0 {
  348. finalId = util.IntAll((*lastInfo)[0]["id"])
  349. }
  350. util.Debug("taskIterateSql---", "finally id", finalId)
  351. lastid, count := 0, 0
  352. for {
  353. util.Debug("重新查询,lastid---", lastid)
  354. 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)
  355. rows, err := MysqlTool1.DB.Query(q)
  356. if err != nil {
  357. util.Debug("taskIterateSql---", err)
  358. }
  359. columns, err := rows.Columns()
  360. if finalId == lastid {
  361. util.Debug("----finish----------", count)
  362. break
  363. }
  364. for rows.Next() {
  365. scanArgs := make([]interface{}, len(columns))
  366. values := make([]interface{}, len(columns))
  367. ret := make(map[string]interface{})
  368. for k := range values {
  369. scanArgs[k] = &values[k]
  370. }
  371. err = rows.Scan(scanArgs...)
  372. if err != nil {
  373. util.Debug("taskIterateSql---", err)
  374. break
  375. }
  376. for i, col := range values {
  377. if v, ok := col.([]uint8); ok {
  378. ret[columns[i]] = string(v)
  379. } else {
  380. ret[columns[i]] = col
  381. }
  382. }
  383. lastid = util.IntAll(ret["id"])
  384. count++
  385. if count%20000 == 0 {
  386. util.Debug("current-------", count, lastid)
  387. }
  388. pool <- true
  389. wg.Add(1)
  390. go func(tmp map[string]interface{}) {
  391. defer func() {
  392. <-pool
  393. wg.Done()
  394. }()
  395. redis.PutCKV("ent_id", util.ObjToString(tmp["name"]),
  396. fmt.Sprintf("%s_%s_%s", util.ObjToString(tmp["name_id"]), util.ObjToString(tmp["area_code"]), util.ObjToString(tmp["city_code"])))
  397. }(ret)
  398. ret = make(map[string]interface{})
  399. }
  400. _ = rows.Close()
  401. wg.Wait()
  402. }
  403. }
  404. var EsField = []string{"_id", "projectname", "owner", "area", "city", "district", "nature_code", "ownerclass_code", "project_stage_code", "category_code", "total_investment", "lasttime", "proposed_id"}
  405. func esDisp() {
  406. sess := MgoPro.GetMgoConn()
  407. defer MgoPro.DestoryMongoConn(sess)
  408. client := Es.GetEsConn()
  409. defer Es.DestoryEsConn(client)
  410. ch := make(chan bool, config.Conf.Serve.Thread)
  411. wg := &sync.WaitGroup{}
  412. var q bson.M
  413. if pici > 0 {
  414. q = bson.M{"pici": bson.M{"$gt": pici}}
  415. }
  416. query := sess.DB(config.Conf.DB.MongoP.Dbname).C(config.Conf.Serve.ProColl).Find(q).Select(SelectF).Iter()
  417. count := 0
  418. for tmp := make(map[string]interface{}); query.Next(tmp); count++ {
  419. if count%200 == 0 {
  420. log.Info(fmt.Sprintf("current --- %d", count))
  421. }
  422. if t := util.Int64All(tmp["pici"]); t > pici {
  423. pici = t
  424. }
  425. ch <- true
  426. wg.Add(1)
  427. go func(tmp map[string]interface{}) {
  428. defer func() {
  429. <-ch
  430. wg.Done()
  431. }()
  432. save := make(map[string]interface{})
  433. for _, f := range EsField {
  434. if tmp[f] == nil {
  435. continue
  436. }
  437. if f == "_id" {
  438. save["proposed_id"] = mongodb.BsonIdToSId(tmp["_id"])
  439. save["_id"] = mongodb.BsonIdToSId(tmp["_id"])
  440. } else if f == "area" {
  441. save[f] = tmp[f]
  442. save["area_code"] = AreaCode[util.ObjToString(tmp["area"])]
  443. if util.ObjToString(tmp["city"]) != "" {
  444. save["area_city"] = tmp["city"]
  445. } else {
  446. save["area_city"] = tmp["area"]
  447. }
  448. } else if f == "lasttime" {
  449. save[f] = util.Int64All(tmp[f]) * 1000
  450. } else if f == "nature_code" {
  451. save[f] = tmp[f]
  452. save["nature"] = TagCode["nature"].(map[string]interface{})[util.ObjToString(tmp[f])]
  453. } else if f == "ownerclass_code" {
  454. save[f] = tmp[f]
  455. save["ownerclass"] = TagCode["owner"].(map[string]interface{})[util.ObjToString(tmp[f])]
  456. } else if f == "project_stage_code" {
  457. save[f] = tmp[f]
  458. save["project_stage"] = TagCode["project_stage"].(map[string]interface{})[util.ObjToString(tmp[f])]
  459. } else if f == "category_code" {
  460. save[f] = tmp[f]
  461. save["category"] = TagCode["category"].(map[string]interface{})[util.ObjToString(tmp[f])]
  462. } else if f == "total_investment" {
  463. text := util.ObjToString(tmp[f])
  464. c := ObjToMoney(text)
  465. c = c / 10000
  466. if c != 0 {
  467. c, _ = util.FormatFloat(c, 4)
  468. save[f] = c
  469. }
  470. } else {
  471. save[f] = tmp[f]
  472. }
  473. }
  474. saveEsPool <- save
  475. }(tmp)
  476. tmp = make(map[string]interface{})
  477. }
  478. wg.Wait()
  479. log.Info(fmt.Sprintf("over --- %d", count))
  480. TaskSingle = true
  481. }
  482. func saveMethod() {
  483. arru := make([]map[string]interface{}, saveSize)
  484. indexu := 0
  485. for {
  486. select {
  487. case v := <-savePool:
  488. arru[indexu] = v
  489. indexu++
  490. if indexu == saveSize {
  491. saveSp <- true
  492. go func(arru []map[string]interface{}) {
  493. defer func() {
  494. <-saveSp
  495. }()
  496. MgoBid.SaveBulk("nzj_bidding", arru...)
  497. }(arru)
  498. arru = make([]map[string]interface{}, saveSize)
  499. indexu = 0
  500. }
  501. case <-time.After(1000 * time.Millisecond):
  502. if indexu > 0 {
  503. saveSp <- true
  504. go func(arru []map[string]interface{}) {
  505. defer func() {
  506. <-saveSp
  507. }()
  508. MgoBid.SaveBulk("nzj_bidding", arru...)
  509. }(arru[:indexu])
  510. arru = make([]map[string]interface{}, saveSize)
  511. indexu = 0
  512. }
  513. }
  514. }
  515. }
  516. func SaveEs() {
  517. arru := make([]map[string]interface{}, EsBulkSize)
  518. indexu := 0
  519. for {
  520. select {
  521. case v := <-saveEsPool:
  522. arru[indexu] = v
  523. indexu++
  524. if indexu == EsBulkSize {
  525. saveEsSp <- true
  526. go func(arru []map[string]interface{}) {
  527. defer func() {
  528. <-saveEsSp
  529. }()
  530. Es.BulkSave(config.Conf.DB.Es.IndexP, arru)
  531. }(arru)
  532. arru = make([]map[string]interface{}, EsBulkSize)
  533. indexu = 0
  534. }
  535. case <-time.After(1000 * time.Millisecond):
  536. if indexu > 0 {
  537. saveEsSp <- true
  538. go func(arru []map[string]interface{}) {
  539. defer func() {
  540. <-saveEsSp
  541. }()
  542. Es.BulkSave(config.Conf.DB.Es.IndexP, arru)
  543. }(arru[:indexu])
  544. arru = make([]map[string]interface{}, EsBulkSize)
  545. indexu = 0
  546. }
  547. }
  548. }
  549. }