main.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "log"
  6. //"math"
  7. mu "mfw/util"
  8. "net"
  9. //"os"
  10. du "jy/util"
  11. "qfw/util"
  12. "qfw/util/mongodb"
  13. "qfw/util/redis"
  14. "sync"
  15. "time"
  16. "gopkg.in/mgo.v2/bson"
  17. )
  18. /*
  19. 从extract_result表中抽到projectset表中,根据3选2判断是不是同一条信息,抽取信息至少有两个字段。
  20. 可以使用redis
  21. //对时间的判断
  22. */
  23. var MultiThread chan bool
  24. var (
  25. Sysconfig map[string]interface{}
  26. MQFW mongodb.MongodbSim
  27. extractColl, projectColl string
  28. lenprojectname int
  29. udpclient mu.UdpClient //udp对象
  30. nextNode []map[string]interface{} //下节点数组
  31. toaddr = []*net.UDPAddr{} //下节点对象
  32. )
  33. const (
  34. REDISIDS = "ids"
  35. REDISKEYS = "keys"
  36. INFOID = "info"
  37. INFOTIMEOUT = 86400 * 30
  38. )
  39. func init() {
  40. initarea()
  41. du.SetConsole(false)
  42. du.SetRollingDaily("./", "project.log")
  43. du.SetLevel(du.DEBUG)
  44. util.ReadConfig(&Sysconfig)
  45. MultiThread = make(chan bool, util.IntAllDef(Sysconfig["thread"], 200))
  46. lenprojectname = util.IntAllDef(Sysconfig["lenprojectname"], 20) - 1
  47. redis.InitRedisBySize(Sysconfig["redisaddrs"].(string), util.IntAllDef(Sysconfig["redisPoolSize"], 100), 30, 300)
  48. MQFW = mongodb.MongodbSim{
  49. MongodbAddr: Sysconfig["mongodbServers"].(string),
  50. Size: util.IntAll(Sysconfig["mongodbPoolSize"]),
  51. DbName: Sysconfig["mongodbName"].(string),
  52. }
  53. MQFW.InitPool()
  54. extractColl = Sysconfig["extractColl"].(string)
  55. projectColl = Sysconfig["projectColl"].(string)
  56. nextNode = util.ObjArrToMapArr(Sysconfig["nextNode"].([]interface{}))
  57. for _, m := range nextNode {
  58. toaddr = append(toaddr, &net.UDPAddr{
  59. IP: net.ParseIP(m["addr"].(string)),
  60. Port: util.IntAll(m["port"]),
  61. })
  62. }
  63. }
  64. type KeyMap struct {
  65. Lock sync.Mutex
  66. Map map[string]*Key
  67. }
  68. type Key struct {
  69. Arr *[]string
  70. Lock *sync.Mutex
  71. }
  72. func NewKeyMap() *KeyMap {
  73. //k:=&Key{[]string{}}
  74. return &KeyMap{
  75. Map: map[string]*Key{},
  76. }
  77. }
  78. //三组lock,对应的(PNKey)key为项目名称,值对应的是此项目名称对应的项目id数组
  79. var PNKey, PCKey, PBKey = NewKeyMap(), NewKeyMap(), NewKeyMap()
  80. //id-lock
  81. var IdLock = &sync.Mutex{}
  82. func main() {
  83. go checkMapJob()
  84. //先加载所有锁
  85. log.Println("loading data from redis...")
  86. n := 0
  87. km := []*KeyMap{PNKey, PCKey, PBKey}
  88. for pos, key := range []string{"pn_*", "pc_*", "pb_*"} {
  89. res := redis.GetKeysByPattern(REDISKEYS, key)
  90. pk := km[pos]
  91. if res != nil {
  92. //一次500条
  93. num := 0
  94. arr := []string{}
  95. for _, v := range res {
  96. n++
  97. num++
  98. k := string(v.([]uint8))
  99. arr = append(arr, k) //根据正则找到key
  100. if num == 500 {
  101. num = 0
  102. ret := redis.Mget(REDISKEYS, arr) //根据key批量取内容
  103. if len(ret) > 0 {
  104. for k1, v1 := range ret {
  105. if v1 != nil {
  106. var a1 []string
  107. json.Unmarshal(v1.([]uint8), &a1)
  108. pk.Map[arr[k1]] = &Key{&a1, &sync.Mutex{}} //pn_项目名称 id数组
  109. }
  110. }
  111. }
  112. arr = []string{}
  113. }
  114. }
  115. if num > 0 {
  116. ret := redis.Mget(REDISKEYS, arr)
  117. if len(ret) > 0 {
  118. for k1, v1 := range ret {
  119. if v1 != nil {
  120. var a1 []string
  121. json.Unmarshal(v1.([]uint8), &a1)
  122. pk.Map[arr[k1]] = &Key{&a1, &sync.Mutex{}}
  123. }
  124. }
  125. }
  126. arr = []string{}
  127. }
  128. }
  129. }
  130. log.Println("load data from redis finished.", n)
  131. //清理redis
  132. //clearedis()
  133. updport := Sysconfig["udpport"].(string)
  134. udpclient = mu.UdpClient{Local: updport, BufSize: 1024}
  135. udpclient.Listen(processUdpMsg)
  136. log.Println("Udp服务监听", updport)
  137. time.Sleep(99999 * time.Hour)
  138. }
  139. func processUdpMsg(act byte, data []byte, ra *net.UDPAddr) {
  140. switch act {
  141. case mu.OP_TYPE_DATA: //上个节点的数据
  142. var mapInfo map[string]interface{}
  143. err := json.Unmarshal(data, &mapInfo)
  144. log.Println("err:", err, "mapInfo:", mapInfo)
  145. if err != nil {
  146. udpclient.WriteUdp([]byte("err:"+err.Error()), mu.OP_NOOP, ra)
  147. } else if mapInfo != nil {
  148. key, _ := mapInfo["key"].(string)
  149. if key == "" {
  150. key = "udpok"
  151. }
  152. go udpclient.WriteUdp([]byte(key), mu.OP_NOOP, ra)
  153. SingleThread <- true
  154. go task(data, mapInfo)
  155. }
  156. case mu.OP_NOOP: //下个节点回应
  157. ok := string(data)
  158. if ok != "" {
  159. log.Println("ok:", ok)
  160. udptaskmap.Delete(ok)
  161. }
  162. }
  163. }
  164. var SingleThread = make(chan bool, 1)
  165. func task(data []byte, mapInfo map[string]interface{}) {
  166. defer func() {
  167. <-SingleThread
  168. }()
  169. defer util.Catch()
  170. q, _ := mapInfo["query"].(map[string]interface{})
  171. if q == nil {
  172. q = map[string]interface{}{
  173. "_id": map[string]interface{}{
  174. "$gt": util.StringTOBsonId(mapInfo["gtid"].(string)),
  175. "$lte": util.StringTOBsonId(mapInfo["lteid"].(string)),
  176. },
  177. }
  178. }
  179. sess := MQFW.GetMgoConn()
  180. defer MQFW.DestoryMongoConn(sess)
  181. //数据正序处理
  182. it := sess.DB(MQFW.DbName).C(extractColl).Find(&q).Iter() //.Sort("publishtime")
  183. count, index := 0, 0
  184. pici := time.Now().Unix()
  185. //log.Println(q, MQFW.DbName, extractColl)
  186. wg := &sync.WaitGroup{}
  187. idmap := &sync.Map{}
  188. for tmp := make(map[string]interface{}); it.Next(tmp); {
  189. // if util.IntAll(tmp["extracttype"]) == -1 {
  190. // tmp = make(map[string]interface{})
  191. // continue
  192. // }
  193. if index%10000 == 0 {
  194. log.Println(index, tmp["_id"])
  195. }
  196. index++
  197. if util.IntAll(tmp["repeat"]) == 1 {
  198. tmp = make(map[string]interface{})
  199. continue
  200. }
  201. count++
  202. thisid := util.BsonIdToSId(tmp["_id"])
  203. b, err := redis.Exists(INFOID, thisid)
  204. if err != nil {
  205. log.Println("checkid err", err.Error())
  206. }
  207. if !b { // && util.IntAll(tmp["infoformat"]) < 2 && tmp["detail"] != nil {
  208. //增加判重逻辑,重复id不再生成
  209. wg.Add(1)
  210. idmap.Store(tmp["_id"], true)
  211. MultiThread <- true
  212. go func(tmp map[string]interface{}, thisid string) {
  213. defer func() {
  214. <-MultiThread
  215. wg.Done()
  216. idmap.Delete(tmp["_id"])
  217. }()
  218. sflag := Compare(tmp, pici)
  219. redis.Put(INFOID, thisid, 1, INFOTIMEOUT)
  220. go IS.Add(sflag)
  221. }(tmp, thisid)
  222. }
  223. if count%500 == 0 {
  224. log.Println("count:", count)
  225. }
  226. tmp = make(map[string]interface{})
  227. }
  228. for {
  229. time.Sleep(5 * time.Second)
  230. n := 0
  231. idmap.Range(func(key interface{}, v interface{}) bool {
  232. n++
  233. log.Println(key, v)
  234. return true
  235. })
  236. if n < 1 {
  237. break
  238. }
  239. }
  240. wg.Wait()
  241. log.Println("task over...", index, count)
  242. //发送udp,调用生成项目索引
  243. mapInfo["stype"] = "project"
  244. if mapInfo["stop"] == nil && len(toaddr) > 0 {
  245. for n, to := range toaddr {
  246. key := fmt.Sprintf("%d-%s-%d", pici, "project", n)
  247. mapInfo["query"] = map[string]interface{}{
  248. "pici": pici,
  249. }
  250. mapInfo["key"] = key
  251. datas, _ := json.Marshal(mapInfo)
  252. node := &udpNode{datas, to, time.Now().Unix(), 0}
  253. udptaskmap.Store(key, node)
  254. udpclient.WriteUdp(datas, mu.OP_TYPE_DATA, to)
  255. }
  256. }
  257. }
  258. func NewPushInfo(tmp map[string]interface{}) bson.M {
  259. return bson.M{
  260. "comeintime": tmp["comeintime"],
  261. "publishtime": tmp["publishtime"],
  262. "title": tmp["title"],
  263. "toptype": tmp["toptype"],
  264. "subtype": tmp["subtype"],
  265. "infoformat": tmp["infoformat"],
  266. "infoid": util.BsonIdToSId(tmp["_id"]),
  267. "href": tmp["href"],
  268. "area": tmp["area"],
  269. "city": tmp["city"],
  270. "cresult": tmp["cresult"],
  271. }
  272. }