main.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  1. package main
  2. /**
  3. 招标信息判重
  4. **/
  5. import (
  6. "encoding/json"
  7. "flag"
  8. "fmt"
  9. "github.com/cron"
  10. "gopkg.in/mgo.v2/bson"
  11. "log"
  12. mu "mfw/util"
  13. "net"
  14. "os"
  15. "qfw/util"
  16. "regexp"
  17. "strconv"
  18. "sync"
  19. "time"
  20. )
  21. var (
  22. Sysconfig map[string]interface{} //配置文件
  23. mconf map[string]interface{} //mongodb配置信息
  24. mgo *MongodbSim //mongodb操作对象
  25. task_mgo *MongodbSim //mongodb操作对象
  26. task_collName string
  27. extract string
  28. extract_back string
  29. udpclient mu.UdpClient //udp对象
  30. nextNode []map[string]interface{} //下节点数组
  31. dupdays = 7 //初始化判重范围
  32. DM *datamap //
  33. //正则筛选相关
  34. FilterRegTitle = regexp.MustCompile("^_$")
  35. FilterRegTitle_0 = regexp.MustCompile("^_$")
  36. FilterRegTitle_1 = regexp.MustCompile("^_$")
  37. FilterRegTitle_2 = regexp.MustCompile("^_$")
  38. isMerger bool //是否合并
  39. threadNum int //线程数量
  40. SiteMap map[string]map[string]interface{} //站点map
  41. LowHeavy bool //低质量数据判重
  42. TimingTask bool //是否定时任务
  43. timingSpanDay int64 //时间跨度
  44. timingPubScope int64 //发布时间周期
  45. gtid,lteid,lastid,gtept,ltept string //命令输入
  46. IsFull bool
  47. updatelock sync.Mutex //锁
  48. )
  49. func init() {
  50. flag.StringVar(&lastid, "id", "", "增量加载的lastid") //以小于等于此id开始加载最近几天的数据
  51. flag.StringVar(&gtid, "gtid", "", "历史增量的起始id")
  52. flag.StringVar(&gtept, "gtept", "", "全量gte发布时间")
  53. flag.StringVar(&gtept, "ltept", "", "全量lte发布时间")
  54. flag.Parse()
  55. util.ReadConfig(&Sysconfig)
  56. task_mconf := Sysconfig["task_mongodb"].(map[string]interface{})
  57. task_mgo = &MongodbSim{
  58. MongodbAddr: task_mconf["task_addrName"].(string),
  59. DbName: task_mconf["task_dbName"].(string),
  60. Size: util.IntAllDef(task_mconf["task_pool"], 10),
  61. }
  62. task_mgo.InitPool()
  63. task_collName = task_mconf["task_collName"].(string)
  64. nextNode = util.ObjArrToMapArr(Sysconfig["nextNode"].([]interface{}))
  65. mconf = Sysconfig["mongodb"].(map[string]interface{})
  66. mgo = &MongodbSim{
  67. MongodbAddr: mconf["addr"].(string),
  68. DbName: mconf["db"].(string),
  69. Size: util.IntAllDef(mconf["pool"], 10),
  70. }
  71. mgo.InitPool()
  72. extract = mconf["extract"].(string)
  73. extract_back = mconf["extract_back"].(string)
  74. dupdays = util.IntAllDef(Sysconfig["dupdays"], 3)
  75. //加载数据
  76. DM = NewDatamap(dupdays, lastid)
  77. FilterRegTitle = regexp.MustCompile(util.ObjToString(Sysconfig["specialwords"]))
  78. FilterRegTitle_0 = regexp.MustCompile(util.ObjToString(Sysconfig["specialtitle_0"]))
  79. FilterRegTitle_1 = regexp.MustCompile(util.ObjToString(Sysconfig["specialtitle_1"]))
  80. FilterRegTitle_2 = regexp.MustCompile(util.ObjToString(Sysconfig["specialtitle_2"]))
  81. isMerger = Sysconfig["isMerger"].(bool)
  82. threadNum = util.IntAllDef(Sysconfig["threads"], 1)
  83. LowHeavy = Sysconfig["lowHeavy"].(bool)
  84. TimingTask = Sysconfig["timingTask"].(bool)
  85. timingSpanDay = util.Int64All(Sysconfig["timingSpanDay"])
  86. timingPubScope = util.Int64All(Sysconfig["timingPubScope"])
  87. //站点配置
  88. site := mconf["site"].(map[string]interface{})
  89. SiteMap = make(map[string]map[string]interface{}, 0)
  90. start := int(time.Now().Unix())
  91. sess_site := mgo.GetMgoConn()
  92. defer mgo.DestoryMongoConn(sess_site)
  93. res_site := sess_site.DB(site["dbname"].(string)).C(site["coll"].(string)).Find(map[string]interface{}{}).Sort("_id").Iter()
  94. for site_dict := make(map[string]interface{}); res_site.Next(&site_dict); {
  95. data_map := map[string]interface{}{
  96. "area": util.ObjToString(site_dict["area"]),
  97. "city": util.ObjToString(site_dict["city"]),
  98. "district": util.ObjToString(site_dict["district"]),
  99. "sitetype": util.ObjToString(site_dict["sitetype"]),
  100. "level": util.ObjToString(site_dict["level"]),
  101. "weight": util.ObjToString(site_dict["weight"]),
  102. }
  103. SiteMap[util.ObjToString(site_dict["site"])] = data_map
  104. }
  105. log.Printf("new站点加载用时:%d秒,%d个\n", int(time.Now().Unix())-start, len(SiteMap))
  106. }
  107. func main() {
  108. go checkMapJob()
  109. updport := Sysconfig["udpport"].(string)
  110. udpclient = mu.UdpClient{Local: updport, BufSize: 1024}
  111. udpclient.Listen(processUdpMsg)
  112. log.Println("Udp服务监听", updport)
  113. if TimingTask {
  114. go historyTaskDay()
  115. }
  116. time.Sleep(99999 * time.Hour)
  117. }
  118. //测试组人员使用
  119. func mainT() {
  120. if TimingTask {
  121. go historyTaskDay()
  122. time.Sleep(99999 * time.Hour)
  123. } else {
  124. //IdType = true //打开id字符串模式
  125. IsFull = true //全量判重
  126. sid := "1fffffffffffffffffffffff"
  127. eid := "9fffffffffffffffffffffff"
  128. log.Println("正常判重测试开始")
  129. log.Println(sid, "---", eid)
  130. mapinfo := map[string]interface{}{}
  131. if sid == "" || eid == "" {
  132. log.Println("sid,eid参数不能为空")
  133. os.Exit(0)
  134. }
  135. mapinfo["gtid"] = sid
  136. mapinfo["lteid"] = eid
  137. mapinfo["stop"] = "true"
  138. task([]byte{}, mapinfo)
  139. time.Sleep(99999 * time.Hour)
  140. }
  141. }
  142. func processUdpMsg(act byte, data []byte, ra *net.UDPAddr) {
  143. fmt.Println("接受的段数据")
  144. switch act {
  145. case mu.OP_TYPE_DATA: //上个节点的数据
  146. //从表中开始处理
  147. var mapInfo map[string]interface{}
  148. err := json.Unmarshal(data, &mapInfo)
  149. log.Println("err:", err, "mapInfo:", mapInfo)
  150. if err != nil {
  151. udpclient.WriteUdp([]byte("err:"+err.Error()), mu.OP_NOOP, ra)
  152. } else if mapInfo != nil {
  153. go task(data, mapInfo)
  154. key, _ := mapInfo["key"].(string)
  155. if key == "" {
  156. key = "udpok"
  157. }
  158. udpclient.WriteUdp([]byte(key), mu.OP_NOOP, ra)
  159. }
  160. case mu.OP_NOOP: //下个节点回应
  161. ok := string(data)
  162. if ok != "" {
  163. log.Println("ok:", ok)
  164. udptaskmap.Delete(ok)
  165. }
  166. }
  167. }
  168. //开始判重程序
  169. func task(data []byte, mapInfo map[string]interface{}) {
  170. log.Println("开始数据判重")
  171. defer util.Catch()
  172. //区间id
  173. q := map[string]interface{}{
  174. "_id": map[string]interface{}{
  175. "$gt": StringTOBsonId(mapInfo["gtid"].(string)),
  176. "$lte": StringTOBsonId(mapInfo["lteid"].(string)),
  177. },
  178. }
  179. //全量
  180. if IsFull && gtept!="" && ltept!=""{
  181. log.Println("执行分段模式")
  182. q = map[string]interface{}{
  183. "publishtime": map[string]interface{}{
  184. "$gte": util.Int64All(gtept),
  185. "$lte": util.Int64All(ltept),
  186. },
  187. }
  188. }
  189. log.Println("增量查询条件:",mgo.DbName, extract, q)
  190. sess := mgo.GetMgoConn()
  191. defer mgo.DestoryMongoConn(sess)
  192. it := sess.DB(mgo.DbName).C(extract).Find(&q).Sort("publishtime").Iter()
  193. updateExtract := [][]map[string]interface{}{}
  194. pool := make(chan bool, threadNum)
  195. wg := &sync.WaitGroup{}
  196. n, repeateN := 0, 0
  197. for tmp := make(map[string]interface{}); it.Next(&tmp); n++ {
  198. if n%10000 == 0 {
  199. log.Println("current:", n, tmp["_id"],tmp["publishtime"], "repeateN:", repeateN)
  200. }
  201. source := util.ObjToMap(tmp["jsondata"]) //前置-jsondata判重
  202. if util.IntAll((*source)["sourcewebsite"]) == 1 {
  203. repeateN++
  204. updatelock.Lock()
  205. updateExtract = append(updateExtract, []map[string]interface{}{
  206. map[string]interface{}{
  207. "_id": tmp["_id"],
  208. },
  209. map[string]interface{}{
  210. "$set": map[string]interface{}{
  211. "repeat": 1,
  212. "dataging":0,
  213. "repeat_reason": "sourcewebsite为1,重复",
  214. },
  215. },
  216. })
  217. if len(updateExtract) >= 500 {
  218. mgo.UpSertBulk(extract, updateExtract...)
  219. updateExtract = [][]map[string]interface{}{}
  220. }
  221. updatelock.Unlock()
  222. tmp = make(map[string]interface{})
  223. continue
  224. }
  225. if util.IntAll(tmp["repeat"]) == 1 || util.IntAll(tmp["repeat"]) == -1||
  226. util.IntAll(tmp["dataging"]) == 1 {
  227. if util.IntAll(tmp["repeat"]) == 1 {
  228. repeateN++
  229. }
  230. tmp = make(map[string]interface{})
  231. continue
  232. }
  233. pool <- true
  234. wg.Add(1)
  235. go func(tmp map[string]interface{}) {
  236. defer func() {
  237. <-pool
  238. wg.Done()
  239. }()
  240. info := NewInfo(tmp)
  241. //正常判重
  242. b, source, reason := DM.check(info)
  243. if b { //有重复,生成更新语句,更新抽取和更新招标
  244. repeateN++
  245. var updateID = map[string]interface{}{} //记录更新判重的
  246. updateID["_id"] = StringTOBsonId(info.id)
  247. repeat_ids:=source.repeat_ids
  248. repeat_ids = append(repeat_ids,info.id)
  249. source.repeat_ids = repeat_ids
  250. //替换数据池-更新
  251. DM.replacePoolData(source)
  252. updateExtract = append(updateExtract, []map[string]interface{}{//原始数据打标签
  253. map[string]interface{}{
  254. "_id": StringTOBsonId(source.id),
  255. },
  256. map[string]interface{}{
  257. "$set": map[string]interface{}{
  258. "repeat_ids": repeat_ids,
  259. },
  260. },
  261. })
  262. updateExtract = append(updateExtract, []map[string]interface{}{//重复数据打标签
  263. updateID,
  264. map[string]interface{}{
  265. "$set": map[string]interface{}{
  266. "repeat": 1,
  267. "repeat_reason": reason,
  268. "repeat_id": source.id,
  269. },
  270. },
  271. })
  272. }
  273. }(tmp)
  274. updatelock.Lock()
  275. if len(updateExtract) >=500 {
  276. mgo.UpSertBulk(extract, updateExtract...)
  277. updateExtract = [][]map[string]interface{}{}
  278. }
  279. updatelock.Unlock()
  280. tmp = make(map[string]interface{})
  281. }
  282. wg.Wait()
  283. if len(updateExtract) > 0 {
  284. mgo.UpSertBulk(extract, updateExtract...)
  285. }
  286. log.Println("this task over.", n, "repeateN:", repeateN, mapInfo["stop"])
  287. time.Sleep(30 * time.Second)
  288. //任务完成,开始发送广播通知下面节点
  289. if n >= repeateN && mapInfo["stop"] == nil {
  290. log.Println("判重任务完成发送udp")
  291. for _, to := range nextNode {
  292. sid, _ := mapInfo["gtid"].(string)
  293. eid, _ := mapInfo["lteid"].(string)
  294. key := sid + "-" + eid + "-" + util.ObjToString(to["stype"])
  295. by, _ := json.Marshal(map[string]interface{}{
  296. "gtid": sid,
  297. "lteid": eid,
  298. "stype": util.ObjToString(to["stype"]),
  299. "key": key,
  300. })
  301. addr := &net.UDPAddr{
  302. IP: net.ParseIP(to["addr"].(string)),
  303. Port: util.IntAll(to["port"]),
  304. }
  305. node := &udpNode{by, addr, time.Now().Unix(), 0}
  306. udptaskmap.Store(key, node)
  307. udpclient.WriteUdp(by, mu.OP_TYPE_DATA, addr)
  308. }
  309. }
  310. }
  311. func historyTaskDay() {
  312. defer util.Catch()
  313. for {
  314. start:=time.Now().Unix()
  315. if gtid=="" {
  316. log.Println("请传gtid,否则无法运行")
  317. os.Exit(0)
  318. return
  319. }
  320. if lteid!="" {
  321. //先进行数据迁移
  322. log.Println("开启一次迁移任务",gtid,lteid)
  323. moveHistoryData(gtid,lteid)
  324. gtid = lteid //替换数据
  325. }
  326. //查询表最后一个id
  327. task_sess := task_mgo.GetMgoConn()
  328. defer task_mgo.DestoryMongoConn(task_sess)
  329. q:=map[string]interface{}{
  330. "isused":true,
  331. }
  332. between_time := time.Now().Unix() - (86400 * timingPubScope)//两年周期
  333. it_last := task_sess.DB(task_mgo.DbName).C(task_collName).Find(&q).Sort("-_id").Iter()
  334. for tmp := make(map[string]interface{}); it_last.Next(&tmp); {
  335. lteid = util.ObjToString(tmp["gtid"])
  336. log.Println("查询的最后一个任务Id:",lteid)
  337. break
  338. }
  339. log.Println("查询完毕-先睡眠5分钟",gtid,lteid)
  340. time.Sleep(5 * time.Minute)
  341. sess := mgo.GetMgoConn()//连接器
  342. defer mgo.DestoryMongoConn(sess)
  343. //开始判重
  344. q = map[string]interface{}{
  345. "_id": map[string]interface{}{
  346. "$gt": StringTOBsonId(gtid),
  347. "$lte": StringTOBsonId(lteid),
  348. },
  349. }
  350. log.Println("历史判重查询条件:",q,"时间:", between_time)
  351. it := sess.DB(mgo.DbName).C(extract).Find(&q).Sort("publishtime").Iter()
  352. num,oknum,outnum, deterTime:= int64(0),int64(0),int64(0),int64(0) //计数
  353. updateExtract := [][]map[string]interface{}{}//批量更新mongo数组
  354. pendAllArr:=[][]map[string]interface{}{}//待处理数组
  355. dayArr := []map[string]interface{}{}
  356. for tmp := make(map[string]interface{}); it.Next(&tmp); num++ {
  357. if num%10000 == 0 {
  358. log.Println("正序遍历:", num)
  359. }
  360. source := util.ObjToMap(tmp["jsondata"])
  361. if util.IntAll((*source)["sourcewebsite"]) == 1 {
  362. outnum++
  363. updatelock.Lock()
  364. updateExtract = append(updateExtract, []map[string]interface{}{
  365. map[string]interface{}{
  366. "_id": tmp["_id"],
  367. },
  368. map[string]interface{}{
  369. "$set": map[string]interface{}{
  370. "repeat": 1,
  371. "dataging": 0,
  372. "repeat_reason": "sourcewebsite为1 重复",
  373. },
  374. },
  375. })
  376. if len(updateExtract) >= 200 {
  377. log.Println("sourcewebsite,批量更新")
  378. mgo.UpSertBulk(extract, updateExtract...)
  379. updateExtract = [][]map[string]interface{}{}
  380. }
  381. updatelock.Unlock()
  382. tmp = make(map[string]interface{})
  383. continue
  384. }
  385. //取-符合-发布时间X年内的数据
  386. updatelock.Lock()
  387. if util.IntAll(tmp["dataging"]) == 1 {
  388. pubtime := util.Int64All(tmp["publishtime"])
  389. if pubtime > 0 && pubtime >= between_time {
  390. oknum++
  391. if deterTime==0 {
  392. log.Println("找到第一条符合条件的数据")
  393. deterTime = util.Int64All(tmp["publishtime"])
  394. dayArr = append(dayArr,tmp)
  395. }else {
  396. if pubtime-deterTime >timingSpanDay*86400 {
  397. //新数组重新构建,当前组数据加到全部组数据
  398. pendAllArr = append(pendAllArr,dayArr)
  399. dayArr = []map[string]interface{}{}
  400. deterTime = util.Int64All(tmp["publishtime"])
  401. dayArr = append(dayArr,tmp)
  402. }else {
  403. dayArr = append(dayArr,tmp)
  404. }
  405. }
  406. }else {
  407. outnum++
  408. //不在两年内的也清标记
  409. updateExtract = append(updateExtract, []map[string]interface{}{
  410. map[string]interface{}{
  411. "_id": tmp["_id"],
  412. },
  413. map[string]interface{}{
  414. "$set": map[string]interface{}{
  415. "dataging": 0,
  416. },
  417. },
  418. })
  419. if len(updateExtract) >= 200 {
  420. log.Println("不在周期内符合dataging==1,批量更新")
  421. mgo.UpSertBulk(extract, updateExtract...)
  422. updateExtract = [][]map[string]interface{}{}
  423. }
  424. }
  425. }
  426. updatelock.Unlock()
  427. tmp = make(map[string]interface{})
  428. }
  429. //批量更新标记
  430. updatelock.Lock()
  431. if len(updateExtract) > 0 {
  432. log.Println("分组后,最后更新不进行判重的数据:",len(updateExtract),oknum+outnum)
  433. mgo.UpSertBulk(extract, updateExtract...)
  434. updateExtract = [][]map[string]interface{}{}
  435. }
  436. updatelock.Unlock()
  437. if len(dayArr)>0 {
  438. pendAllArr = append(pendAllArr,dayArr)
  439. dayArr = []map[string]interface{}{}
  440. }
  441. log.Println("查询数量:",num,"符合条件:",oknum)
  442. if len(pendAllArr) <= 0 {
  443. log.Println("没找到dataging==1的数据")
  444. }
  445. //测试分组数量是否正确
  446. testNum:=0
  447. for k,v:=range pendAllArr {
  448. log.Println("第",k,"组--","数量:",len(v))
  449. testNum = testNum+len(v)
  450. }
  451. log.Println("本地构建分组完成:",len(pendAllArr),"组","测试-总计数量:",testNum)
  452. n, repeateN := 0, 0
  453. log.Println("线程数:",threadNum)
  454. pool := make(chan bool, threadNum)
  455. wg := &sync.WaitGroup{}
  456. for k,v:=range pendAllArr { //每组结束更新一波数据
  457. pool <- true
  458. wg.Add(1)
  459. go func(k int, v []map[string]interface{}) {
  460. defer func() {
  461. <-pool
  462. wg.Done()
  463. }()
  464. //每组临时数组 - 互不干扰
  465. groupUpdateExtract := [][]map[string]interface{}{}
  466. //
  467. groupOtherExtract := [][]map[string]interface{}{}
  468. //构建当前组的数据池
  469. log.Println("构建第", k, "组---(数据池)")
  470. //当前组的第一个发布时间
  471. first_pt := util.Int64All(v[len(v)-1]["publishtime"])
  472. curTM := TimedTaskDatamap(dupdays+int(timingSpanDay)+1, first_pt+86400, int(k))
  473. log.Println("开始遍历判重第", k, "组 共计数量:", len(v))
  474. n = n + len(v)
  475. log.Println("统计目前总数量:", n, "重复数量:", repeateN)
  476. for _, tmp := range v {
  477. info := NewInfo(tmp)
  478. b, source, reason := curTM.check(info)
  479. if b { //有重复,生成更新语句,更新抽取和更新招标
  480. repeateN++
  481. //重复数据打标签
  482. repeat_ids:=source.repeat_ids
  483. repeat_ids = append(repeat_ids,info.id)
  484. source.repeat_ids = repeat_ids
  485. //替换数据池-更新
  486. DM.replacePoolData(source)
  487. updatelock.Lock()
  488. //更新数据源- 14 或者 15
  489. //判断是否在当前段落
  490. if judgeIsCurIds(gtid,lteid,source.id) {
  491. groupUpdateExtract = append(groupUpdateExtract, []map[string]interface{}{//重复数据打标签
  492. map[string]interface{}{
  493. "_id": StringTOBsonId(source.id),
  494. },
  495. map[string]interface{}{
  496. "$set": map[string]interface{}{
  497. "repeat_ids": repeat_ids,
  498. },
  499. },
  500. })
  501. }else {
  502. groupOtherExtract = append(groupOtherExtract, []map[string]interface{}{//重复数据打标签
  503. map[string]interface{}{
  504. "_id": StringTOBsonId(source.id),
  505. },
  506. map[string]interface{}{
  507. "$set": map[string]interface{}{
  508. "repeat_ids": repeat_ids,
  509. },
  510. },
  511. })
  512. }
  513. groupUpdateExtract = append(groupUpdateExtract, []map[string]interface{}{
  514. map[string]interface{}{
  515. "_id": tmp["_id"],
  516. },
  517. map[string]interface{}{
  518. "$set": map[string]interface{}{
  519. "repeat": 1,
  520. "repeat_reason": reason,
  521. "repeat_id": source.id,
  522. "dataging": 0,
  523. },
  524. },
  525. })
  526. if len(groupUpdateExtract) >= 500 {
  527. mgo.UpSertBulk(extract, groupUpdateExtract...)
  528. groupUpdateExtract = [][]map[string]interface{}{}
  529. }
  530. if len(groupOtherExtract) >= 500 {
  531. mgo.UpSertBulk(extract_back, groupOtherExtract...)
  532. groupOtherExtract = [][]map[string]interface{}{}
  533. }
  534. updatelock.Unlock()
  535. } else {
  536. updatelock.Lock()
  537. groupUpdateExtract = append(groupUpdateExtract, []map[string]interface{}{
  538. map[string]interface{}{
  539. "_id": tmp["_id"],
  540. },
  541. map[string]interface{}{
  542. "$set": map[string]interface{}{
  543. "dataging": 0, //符合条件的都为dataging==0
  544. },
  545. },
  546. })
  547. if len(groupUpdateExtract) >= 500 {
  548. mgo.UpSertBulk(extract, groupUpdateExtract...)
  549. groupUpdateExtract = [][]map[string]interface{}{}
  550. }
  551. updatelock.Unlock()
  552. }
  553. }
  554. //每组数据结束-更新数据
  555. updatelock.Lock()
  556. if len(groupUpdateExtract) > 0 {
  557. mgo.UpSertBulk(extract, groupUpdateExtract...)
  558. }
  559. if len(groupOtherExtract) > 0 {
  560. mgo.UpSertBulk(extract_back, groupOtherExtract...)
  561. }
  562. updatelock.Unlock()
  563. }(k, v)
  564. }
  565. wg.Wait()
  566. //任务完成,开始发送广播通知下面节点 发udp 去升索引待定 + 合并
  567. if n >= repeateN && gtid!=lteid{
  568. for _, to := range nextNode {
  569. next_sid := util.BsonIdToSId(gtid)
  570. next_eid := util.BsonIdToSId(lteid)
  571. key := next_sid + "-" + next_eid + "-" + util.ObjToString(to["stype"])
  572. by, _ := json.Marshal(map[string]interface{}{
  573. "gtid": next_sid,
  574. "lteid": next_eid,
  575. "stype": util.ObjToString(to["stype"]),
  576. "key": key,
  577. })
  578. addr := &net.UDPAddr{
  579. IP: net.ParseIP(to["addr"].(string)),
  580. Port: util.IntAll(to["port"]),
  581. }
  582. node := &udpNode{by, addr, time.Now().Unix(), 0}
  583. udptaskmap.Store(key, node)
  584. udpclient.WriteUdp(by, mu.OP_TYPE_DATA, addr)
  585. }
  586. }
  587. end:=time.Now().Unix()
  588. log.Println("this timeTask over.", n, "repeateN:", repeateN,gtid,lteid)
  589. log.Println(gtid,lteid)
  590. if end-start<60*5 {
  591. log.Println("睡眠.............")
  592. time.Sleep(5 * time.Minute)
  593. }
  594. log.Println("继续下一段的历史判重")
  595. }
  596. }
  597. //判断是否在当前id段落
  598. func judgeIsCurIds (gtid string,lteid string,curid string) bool {
  599. gt_time, _ := strconv.ParseInt(gtid[:8], 16, 64)
  600. lte_time, _ := strconv.ParseInt(lteid[:8], 16, 64)
  601. cur_time, _ := strconv.ParseInt(curid[:8], 16, 64)
  602. if cur_time>gt_time&&cur_time<=lte_time {
  603. return true
  604. }
  605. return false
  606. }
  607. //迁移上一段数据
  608. func moveHistoryData(startid string,endid string) {
  609. sess := mgo.GetMgoConn()
  610. defer mgo.DestoryMongoConn(sess)
  611. year, month, day := time.Now().Date()
  612. q := map[string]interface{}{
  613. "_id": map[string]interface{}{
  614. "$gt": StringTOBsonId(startid),
  615. "$lte": StringTOBsonId(endid),
  616. },
  617. }
  618. log.Println(q)
  619. it := sess.DB(mgo.DbName).C(extract).Find(&q).Iter()
  620. index := 0
  621. for tmp := make(map[string]interface{}); it.Next(&tmp); index++ {
  622. mgo.Save(extract_back, tmp)
  623. tmp = map[string]interface{}{}
  624. if index%1000 == 0 {
  625. log.Println("index", index)
  626. }
  627. }
  628. log.Println("save to", extract_back, " ok index", index)
  629. qv := map[string]interface{}{
  630. "comeintime": map[string]interface{}{
  631. "$lt": time.Date(year, month, day, 0, 0, 0, 0, time.Local).Add(-time.Duration(dupdays+1) * 24 * time.Hour*2).Unix(),
  632. },
  633. }
  634. delnum := mgo.Delete(extract, qv)
  635. log.Println("remove from ", extract, delnum)
  636. }
  637. func moveTimeoutData() {
  638. log.Println("部署迁移定时任务")
  639. c := cron.New()
  640. c.AddFunc("0 0 0 * * ?", func() { moveOnceTimeOut() })
  641. c.Start()
  642. }
  643. func moveOnceTimeOut() {
  644. log.Println("执行一次迁移超时数据")
  645. sess := mgo.GetMgoConn()
  646. defer mgo.DestoryMongoConn(sess)
  647. now:=time.Now()
  648. move_time := time.Date(now.Year()-2, now.Month(), now.Day(), 0, 0, 0, 0, time.Local)
  649. task_id := util.BsonIdToSId(bson.NewObjectIdWithTime(move_time))
  650. q := map[string]interface{}{
  651. "_id": map[string]interface{}{
  652. "$lt": StringTOBsonId(task_id),
  653. },
  654. }
  655. it := sess.DB(mgo.DbName).C("result_20200714").Find(&q).Iter()
  656. index := 0
  657. for tmp := make(map[string]interface{}); it.Next(&tmp); index++ {
  658. if index%10000 == 0 {
  659. log.Println("index", index)
  660. }
  661. del_id:=BsonTOStringId(tmp["_id"])
  662. mgo.Save("result_20200713", tmp)
  663. mgo.DeleteById("result_20200714",del_id)
  664. tmp = map[string]interface{}{}
  665. }
  666. log.Println("save and delete", " ok index", index)
  667. }