main.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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. if err := rootCmd.Execute(); err != nil {
  39. fmt.Println("rootCmd.Execute failed", err.Error())
  40. }
  41. }
  42. func tags() *cobra.Command {
  43. cmdClient := &cobra.Command{
  44. Use: "tags",
  45. Short: "Start processing tags data",
  46. Run: func(cmd *cobra.Command, args []string) {
  47. InitRule()
  48. go UpdateMethod()
  49. taskRun()
  50. c := make(chan bool, 1)
  51. <-c
  52. },
  53. }
  54. return cmdClient
  55. }
  56. func project() *cobra.Command {
  57. cmdClient := &cobra.Command{
  58. Use: "project",
  59. Short: "Start processing project data",
  60. Run: func(cmd *cobra.Command, args []string) {
  61. InitRule()
  62. loadProject()
  63. go updateAllQueue()
  64. UdpClient = udp.UdpClient{Local: config.Conf.Udp.LocPort, BufSize: 1024}
  65. UdpClient.Listen(processUdpMsg)
  66. log.Info("Udp服务监听", zap.String("port:", config.Conf.Udp.LocPort))
  67. c := make(chan bool, 1)
  68. <-c
  69. },
  70. }
  71. return cmdClient
  72. }
  73. func nzjData() *cobra.Command {
  74. cmdClient := &cobra.Command{
  75. Use: "nzj-data",
  76. Short: "Start processing project data",
  77. Run: func(cmd *cobra.Command, args []string) {
  78. if LastId == "" {
  79. _ = cmd.Help()
  80. os.Exit(0)
  81. }
  82. go saveMethod()
  83. sid, eid := taskQ()
  84. if sid != "" && eid != "" {
  85. doTask1(sid, eid)
  86. LastId = eid
  87. }
  88. crn := cron.New()
  89. cronstr := "0 */10 * * * ?" // 每10min执行一次
  90. _ = crn.AddFunc(cronstr, func() {
  91. if TaskSingle {
  92. sid, eid := taskQ()
  93. if sid != "" && eid != "" {
  94. TaskSingle = false
  95. doTask1(sid, eid)
  96. LastId = eid
  97. }
  98. } else {
  99. log.Info("上次任务未执行完成")
  100. }
  101. })
  102. crn.Start()
  103. c := make(chan bool, 1)
  104. <-c
  105. },
  106. }
  107. cmdClient.Flags().StringVarP(&LastId, "lastid", "s", "", "data start id")
  108. return cmdClient
  109. }
  110. func projectAdd() *cobra.Command {
  111. cmdClient := &cobra.Command{
  112. Use: "project-add",
  113. Short: "Start processing project data",
  114. Run: func(cmd *cobra.Command, args []string) {
  115. if LastId == "" {
  116. _ = cmd.Help()
  117. os.Exit(0)
  118. }
  119. InitRule()
  120. loadProject()
  121. go updateAllQueue()
  122. info, _ := MgoBid.Find("nzj_bidding", nil, `{"_id": -1}`, nil, true, -1, 1)
  123. doTask(LastId, mongodb.BsonIdToSId((*info)[0]["_id"]))
  124. LastId = mongodb.BsonIdToSId((*info)[0]["_id"])
  125. crn := cron.New()
  126. cronstr := "0 */30 * * * ?" // 每30min执行一次
  127. _ = crn.AddFunc(cronstr, func() {
  128. if TaskSingle {
  129. info, _ := MgoBid.Find("nzj_bidding", nil, `{"_id": -1}`, nil, true, -1, 1)
  130. TaskSingle = false
  131. doTask(LastId, mongodb.BsonIdToSId((*info)[0]["_id"]))
  132. LastId = mongodb.BsonIdToSId((*info)[0]["_id"])
  133. } else {
  134. log.Info("上次任务未执行完成")
  135. }
  136. })
  137. crn.Start()
  138. c := make(chan bool, 1)
  139. <-c
  140. },
  141. }
  142. cmdClient.Flags().StringVarP(&LastId, "lastid", "s", "", "data start id")
  143. return cmdClient
  144. }
  145. func tidbSave() *cobra.Command {
  146. cmdClient := &cobra.Command{
  147. Use: "tidb",
  148. Short: "Start processing project save to tidb",
  149. Run: func(cmd *cobra.Command, args []string) {
  150. InitMysql()
  151. InitArea()
  152. go SaveFunc("dwd_f_nzj_baseinfo_new", BaseField)
  153. go SaveRFunc("dwd_f_nzj_follw_record_new", RecordField)
  154. go SaveCFunc("dwd_f_nzj_contact_new", ContactField)
  155. go SaveCyFunc("dwd_f_nzj_category_tags_new", CategoryField)
  156. go SaveEntFunc("dwd_f_nzj_ent_new", EntField)
  157. redis.InitRedis1("ent_id=172.17.4.189:8379", 6) // name_id
  158. taskTidb(nil)
  159. c := make(chan bool, 1)
  160. <-c
  161. },
  162. }
  163. return cmdClient
  164. }
  165. func tidbAddSave() *cobra.Command {
  166. cmdClient := &cobra.Command{
  167. Use: "tidb-add",
  168. Short: "Start processing project save to tidb",
  169. Run: func(cmd *cobra.Command, args []string) {
  170. InitMysql()
  171. InitArea()
  172. //go SaveFunc("dwd_f_nzj_baseinfo", BaseField)
  173. //go SaveRFunc("dwd_f_nzj_follw_record", RecordField)
  174. //go SaveCFunc("dwd_f_nzj_contact", ContactField)
  175. //go SaveCyFunc("dwd_f_nzj_category_tags", CategoryField)
  176. redis.InitRedis1("ent_id=172.17.4.189:8379", 6) // name_id
  177. taskTidb_add(bson.M{"pici": bson.M{"$gt": pici}})
  178. crn := cron.New()
  179. cronstr := "0 */30 * * * ?" // 每30min执行一次
  180. _ = crn.AddFunc(cronstr, func() {
  181. if TaskSingle {
  182. TaskSingle = false
  183. taskTidb_add(bson.M{"pici": bson.M{"$gt": pici}})
  184. } else {
  185. log.Info("上次任务未执行完成")
  186. }
  187. })
  188. crn.Start()
  189. c := make(chan bool, 1)
  190. <-c
  191. },
  192. }
  193. cmdClient.Flags().Int64VarP(&pici, "pici", "c", 0, "pici time")
  194. return cmdClient
  195. }
  196. func redisSave() *cobra.Command {
  197. cmdClient := &cobra.Command{
  198. Use: "redis",
  199. Short: "Start processing project save to tidb",
  200. Run: func(cmd *cobra.Command, args []string) {
  201. InitMysql()
  202. redis.InitRedis1("ent_id=172.17.4.189:8379", 6) // name_id
  203. redisDisp()
  204. },
  205. }
  206. return cmdClient
  207. }
  208. func esSave() *cobra.Command {
  209. cmdClient := &cobra.Command{
  210. Use: "es-save",
  211. Short: "Start processing project save to es",
  212. Run: func(cmd *cobra.Command, args []string) {
  213. InitMysql()
  214. InitArea()
  215. InitTagCode()
  216. InitEs()
  217. go SaveEs()
  218. esDisp()
  219. c := make(chan bool, 1)
  220. <-c
  221. },
  222. }
  223. return cmdClient
  224. }
  225. func processUdpMsg(act byte, data []byte, ra *net.UDPAddr) {
  226. switch act {
  227. case udp.OP_TYPE_DATA:
  228. var mapInfo map[string]interface{}
  229. err := json.Unmarshal(data, &mapInfo)
  230. log.Info("processUdpMsg", zap.Any("mapInfo:", mapInfo))
  231. gtid, _ := mapInfo["gtid"].(string)
  232. lteid, _ := mapInfo["lteid"].(string)
  233. if err != nil || gtid == "" || lteid == "" {
  234. UdpClient.WriteUdp([]byte("tidb udp error"), udp.OP_NOOP, ra)
  235. } else {
  236. //udp成功回写
  237. if k := util.ObjToString(mapInfo["key"]); k != "" {
  238. UdpClient.WriteUdp([]byte(k), udp.OP_NOOP, ra)
  239. } else {
  240. k = fmt.Sprintf("%s-%s-%s", gtid, lteid, util.ObjToString(mapInfo["stype"]))
  241. UdpClient.WriteUdp([]byte(k), udp.OP_NOOP, ra)
  242. }
  243. log.Info("start merge ...")
  244. doTask(gtid, lteid)
  245. }
  246. case udp.OP_NOOP: //下个节点回应
  247. }
  248. }
  249. func taskQ() (string, string) {
  250. log.Info("taskQ", zap.String("lastid", LastId))
  251. query := bson.M{"gtid": bson.M{"$gt": LastId}, "dataprocess": 8}
  252. info, _ := MgoBid.Find("bidding_processing_ids", query, `{"_id": -1}`, nil, false, -1, 1)
  253. if len(*info) > 0 {
  254. newid := util.ObjToString((*info)[0]["lteid"])
  255. log.Info("taskQ", zap.String("新lastid", newid))
  256. return LastId, newid
  257. } else {
  258. log.Info("taskQ 未发现新数据")
  259. return "", ""
  260. }
  261. }
  262. func redisDisp() {
  263. pool := make(chan bool, 5) //控制线程数
  264. wg := &sync.WaitGroup{}
  265. finalId := 0
  266. lastInfo := MysqlTool1.SelectBySql(fmt.Sprintf("SELECT id FROM %s ORDER BY id DESC LIMIT 1", "dws_f_ent_baseinfo"))
  267. if len(*lastInfo) > 0 {
  268. finalId = util.IntAll((*lastInfo)[0]["id"])
  269. }
  270. util.Debug("taskIterateSql---", "finally id", finalId)
  271. lastid, count := 0, 0
  272. for {
  273. util.Debug("重新查询,lastid---", lastid)
  274. 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)
  275. rows, err := MysqlTool1.DB.Query(q)
  276. if err != nil {
  277. util.Debug("taskIterateSql---", err)
  278. }
  279. columns, err := rows.Columns()
  280. if finalId == lastid {
  281. util.Debug("----finish----------", count)
  282. break
  283. }
  284. for rows.Next() {
  285. scanArgs := make([]interface{}, len(columns))
  286. values := make([]interface{}, len(columns))
  287. ret := make(map[string]interface{})
  288. for k := range values {
  289. scanArgs[k] = &values[k]
  290. }
  291. err = rows.Scan(scanArgs...)
  292. if err != nil {
  293. util.Debug("taskIterateSql---", err)
  294. break
  295. }
  296. for i, col := range values {
  297. if v, ok := col.([]uint8); ok {
  298. ret[columns[i]] = string(v)
  299. } else {
  300. ret[columns[i]] = col
  301. }
  302. }
  303. lastid = util.IntAll(ret["id"])
  304. count++
  305. if count%20000 == 0 {
  306. util.Debug("current-------", count, lastid)
  307. }
  308. pool <- true
  309. wg.Add(1)
  310. go func(tmp map[string]interface{}) {
  311. defer func() {
  312. <-pool
  313. wg.Done()
  314. }()
  315. redis.PutCKV("ent_id", util.ObjToString(tmp["name"]),
  316. fmt.Sprintf("%s_%s_%s", util.ObjToString(tmp["name_id"]), util.ObjToString(tmp["area_code"]), util.ObjToString(tmp["city_code"])))
  317. }(ret)
  318. ret = make(map[string]interface{})
  319. }
  320. _ = rows.Close()
  321. wg.Wait()
  322. }
  323. }
  324. var EsField = []string{"_id", "projectname", "owner", "area", "city", "district", "nature_code", "ownerclass_code", "project_stage_code", "category_code", "total_investment", "lasttime", "proposed_id"}
  325. func esDisp() {
  326. sess := MgoPro.GetMgoConn()
  327. defer MgoPro.DestoryMongoConn(sess)
  328. client := Es.GetEsConn()
  329. defer Es.DestoryEsConn(client)
  330. ch := make(chan bool, config.Conf.Serve.Thread)
  331. wg := &sync.WaitGroup{}
  332. query := sess.DB(config.Conf.DB.MongoP.Dbname).C(config.Conf.DB.MongoP.Coll).Find(nil).Select(SelectF).Iter()
  333. count := 0
  334. for tmp := make(map[string]interface{}); query.Next(tmp); count++ {
  335. if count%20000 == 0 {
  336. log.Info(fmt.Sprintf("current --- %d", count))
  337. }
  338. ch <- true
  339. wg.Add(1)
  340. go func(tmp map[string]interface{}) {
  341. defer func() {
  342. <-ch
  343. wg.Done()
  344. }()
  345. save := make(map[string]interface{})
  346. for _, f := range EsField {
  347. if tmp[f] == nil {
  348. continue
  349. }
  350. if f == "_id" {
  351. save["proposed_id"] = mongodb.BsonIdToSId(tmp["_id"])
  352. save["_id"] = mongodb.BsonIdToSId(tmp["_id"])
  353. } else if f == "area" {
  354. save[f] = tmp[f]
  355. save["area_code"] = AreaCode[util.ObjToString(tmp["area"])]
  356. if util.ObjToString(tmp["city"]) != "" {
  357. save["area_city"] = tmp["city"]
  358. } else {
  359. save["area_city"] = tmp["area"]
  360. }
  361. } else if f == "lasttime" {
  362. save[f] = util.Int64All(tmp[f]) * 1000
  363. } else if f == "nature_code" {
  364. save[f] = tmp[f]
  365. save["nature"] = TagCode["nature"].(map[string]interface{})[util.ObjToString(tmp[f])]
  366. } else if f == "ownerclass_code" {
  367. save[f] = tmp[f]
  368. save["ownerclass"] = TagCode["owner"].(map[string]interface{})[util.ObjToString(tmp[f])]
  369. } else if f == "project_stage_code" {
  370. save[f] = tmp[f]
  371. save["project_stage"] = TagCode["project_stage"].(map[string]interface{})[util.ObjToString(tmp[f])]
  372. } else if f == "category_code" {
  373. save[f] = tmp[f]
  374. save["category"] = TagCode["category"].(map[string]interface{})[util.ObjToString(tmp[f])]
  375. } else if f == "total_investment" {
  376. text := util.ObjToString(tmp[f])
  377. c := ObjToMoney(text)
  378. c = c / 10000
  379. if c != 0 {
  380. c, _ = util.FormatFloat(c, 4)
  381. save[f] = c
  382. }
  383. } else {
  384. save[f] = tmp[f]
  385. }
  386. }
  387. saveEsPool <- save
  388. }(tmp)
  389. tmp = make(map[string]interface{})
  390. }
  391. wg.Wait()
  392. log.Info(fmt.Sprintf("over --- %d", count))
  393. }
  394. func saveMethod() {
  395. arru := make([]map[string]interface{}, saveSize)
  396. indexu := 0
  397. for {
  398. select {
  399. case v := <-savePool:
  400. arru[indexu] = v
  401. indexu++
  402. if indexu == saveSize {
  403. saveSp <- true
  404. go func(arru []map[string]interface{}) {
  405. defer func() {
  406. <-saveSp
  407. }()
  408. MgoBid.SaveBulk("nzj_bidding", arru...)
  409. }(arru)
  410. arru = make([]map[string]interface{}, saveSize)
  411. indexu = 0
  412. }
  413. case <-time.After(1000 * time.Millisecond):
  414. if indexu > 0 {
  415. saveSp <- true
  416. go func(arru []map[string]interface{}) {
  417. defer func() {
  418. <-saveSp
  419. }()
  420. MgoBid.SaveBulk("nzj_bidding", arru...)
  421. }(arru[:indexu])
  422. arru = make([]map[string]interface{}, saveSize)
  423. indexu = 0
  424. }
  425. }
  426. }
  427. }
  428. func SaveEs() {
  429. arru := make([]map[string]interface{}, EsBulkSize)
  430. indexu := 0
  431. for {
  432. select {
  433. case v := <-saveEsPool:
  434. arru[indexu] = v
  435. indexu++
  436. if indexu == EsBulkSize {
  437. saveEsSp <- true
  438. go func(arru []map[string]interface{}) {
  439. defer func() {
  440. <-saveEsSp
  441. }()
  442. Es.BulkSave(config.Conf.DB.Es.IndexP, arru)
  443. }(arru)
  444. arru = make([]map[string]interface{}, EsBulkSize)
  445. indexu = 0
  446. }
  447. case <-time.After(1000 * time.Millisecond):
  448. if indexu > 0 {
  449. saveEsSp <- true
  450. go func(arru []map[string]interface{}) {
  451. defer func() {
  452. <-saveEsSp
  453. }()
  454. Es.BulkSave(config.Conf.DB.Es.IndexP, arru)
  455. }(arru[:indexu])
  456. arru = make([]map[string]interface{}, EsBulkSize)
  457. indexu = 0
  458. }
  459. }
  460. }
  461. }