From c1e5407407cdb8467f1e261b67e8755c9ac57388 Mon Sep 17 00:00:00 2001 From: aarongao Date: Tue, 10 Mar 2020 15:27:58 +0800 Subject: [PATCH] 替换mongodb驱动 --- .gitignore | 1 + API/Complaint.go | 45 +++++++++++++++++++++++++-------------------- API/DealyMessage.go | 25 +++++++++++++++++++------ API/Icon.go | 35 +++++++++++++++++++++++++---------- API/Investigation.go | 21 +++++++++++++++------ API/Item.go | 33 ++++++++++++++++++++++++--------- API/Line.go | 32 +++++++++++++++++++++++--------- API/Scenic.go | 51 +++++++++++++++++++++++++++++++++++---------------- API/Shop.go | 33 ++++++++++++++++++++++++--------- API/Sms.go | 2 +- API/Tag.go | 36 +++++++++++++++++++++++++++--------- API/TopMenus.go | 33 +++++++++++++++++++++++---------- API/Trajectory.go | 2 +- API/User.go | 44 +++++++++++++++++++++++++++----------------- API/UserLog.go | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---- Bin/Monitor.go | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ DB/db.go | 171 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------------------------------------------------------------------- Lib/DelayMessage/delaymessage.go | 41 +++++++++++++++++++++++------------------ main.go | 110 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------------------------------- main2.go | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 20 files changed, 654 insertions(+), 276 deletions(-) create mode 100644 Bin/Monitor.go create mode 100644 main2.go diff --git a/.gitignore b/.gitignore index de92754..8f07515 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ main tiles Upload Console +Bin/Monitor diff --git a/API/Complaint.go b/API/Complaint.go index 8ea55ab..7573928 100644 --- a/API/Complaint.go +++ b/API/Complaint.go @@ -4,11 +4,13 @@ import ( "encoding/json" "github.com/aarongao/tools" "github.com/gin-gonic/gin" - "gopkg.in/mgo.v2/bson" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo/options" "letu/DB" "math" "regexp" "strconv" + "time" ) // @Title 增加投诉 @@ -27,10 +29,8 @@ import ( // @Failure 500 {object} tools.ResponseError "{"errcode":1,"errmsg":"错误原因"}" // @Router /CreateComplaint? [post] func CreateComplaint(c *gin.Context) { - c.Header("Access-Control-Allow-Origin",c.Request.Header.Get("Origin")) - c.Header("Access-Control-Allow-Credentials","true") - - + c.Header("Access-Control-Allow-Origin", c.Request.Header.Get("Origin")) + c.Header("Access-Control-Allow-Credentials", "true") reg := regexp.MustCompile(Regular) if !reg.MatchString(c.PostForm("Mobile")) { @@ -42,7 +42,7 @@ func CreateComplaint(c *gin.Context) { return } - if c.PostForm("Mobile") == ""{ + if c.PostForm("Mobile") == "" { c.JSON(200, tools.ResponseError{ 1, "手机号为空", @@ -50,9 +50,8 @@ func CreateComplaint(c *gin.Context) { return } - // 检查验证码 - cacheCode := DB.Redis.Get("code_"+c.PostForm("Mobile")) + cacheCode := DB.Redis.Get("code_" + c.PostForm("Mobile")) if cacheCode != c.PostForm("Code") { c.JSON(200, tools.ResponseError{ @@ -67,7 +66,7 @@ func CreateComplaint(c *gin.Context) { json.Unmarshal([]byte(c.PostForm("Image")), &images) - DB.CComplaint.Insert(DB.SComplaint{ + DB.CComplaint.InsertOne(tools.GetContext(), DB.SComplaint{ c.PostForm("Type"), c.PostForm("ScenicId"), c.PostForm("Mobile"), @@ -75,6 +74,8 @@ func CreateComplaint(c *gin.Context) { c.PostForm("Sex"), c.PostForm("Content"), images, + "", + time.Now().Unix(), }) c.JSON(200, tools.ResponseSeccess{ @@ -82,13 +83,8 @@ func CreateComplaint(c *gin.Context) { "ok", }) - } - - - - // @Title 查询所有投诉 // @Description 投诉 - 查询所有投诉 // @Accept json @@ -101,19 +97,28 @@ func AllComplaint(c *gin.Context) { c.Header("Access-Control-Allow-Origin", c.Request.Header.Get("Origin")) c.Header("Access-Control-Allow-Credentials", "true") - total,_ := DB.CComplaint.Find(bson.M{}).Count() - limit,_ := strconv.Atoi(c.Query("Limit")) + total, _ := DB.CComplaint.CountDocuments(tools.GetContext(), bson.M{}) + limit, _ := strconv.ParseInt(c.Query("Limit"),10,64) if limit == 0 { limit = 50 } - currPage, _ := strconv.Atoi(c.Query("Page")) + currPage, _ := strconv.ParseInt(c.Query("Page"),10,64) if currPage == 0 { currPage = 1 } skip := (currPage - 1) * limit - var aComplaint = []DB.SComplaint{} - DB.CComplaint.Find(bson.M{}).Limit(limit).Skip(int(skip)).Sort("-_id").All(&aComplaint) + var aComplaint = []bson.M{} + + cur, err := DB.CComplaint.Find(tools.GetContext(), bson.M{}, &options.FindOptions{Limit: &limit, Skip: &skip, Sort: bson.M{"_id": -1}}) + defer cur.Close(tools.GetContext()) + if err == nil { + for cur.Next(tools.GetContext()) { + var e bson.M + cur.Decode(&e) + aComplaint = append(aComplaint,e) + } + } c.JSON(200, tools.Page{ 0, @@ -124,4 +129,4 @@ func AllComplaint(c *gin.Context) { aComplaint, }) -} \ No newline at end of file +} diff --git a/API/DealyMessage.go b/API/DealyMessage.go index 1212f54..b312328 100644 --- a/API/DealyMessage.go +++ b/API/DealyMessage.go @@ -3,7 +3,8 @@ package Api import ( "github.com/aarongao/tools" "github.com/gin-gonic/gin" - "gopkg.in/mgo.v2/bson" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" "letu/Lib/DelayMessage" "letu/Lib/Token" ) @@ -21,7 +22,8 @@ func DealyMessageInfo(c *gin.Context) { c.Header("Access-Control-Allow-Origin", c.Request.Header.Get("Origin")) c.Header("Access-Control-Allow-Credentials", "true") - if c.Query("Token") == "" || bson.IsObjectIdHex(c.Query("UserId")) == false { + _, err := primitive.ObjectIDFromHex(c.Query("UserId")) + if c.Query("Token") == "" || err != nil { c.JSON(200, tools.ResponseError{ 1, "Token或者用户id不正确", @@ -38,7 +40,15 @@ func DealyMessageInfo(c *gin.Context) { } var aDelayMessage []DelayMessage.Message - DelayMessage.CDelayMessage.Find(bson.M{"UserId": c.Query("UserId")}).All(&aDelayMessage) + cur, err := DelayMessage.CDelayMessage.Find(tools.GetContext(), bson.M{"UserId": c.Query("UserId")}) + defer cur.Close(tools.GetContext()) + if err == nil { + for cur.Next(tools.GetContext()) { + var e DelayMessage.Message + cur.Decode(&e) + aDelayMessage = append(aDelayMessage,e) + } + } if aDelayMessage == nil { aDelayMessage = []DelayMessage.Message{} @@ -66,7 +76,8 @@ func CreateDealyMessage(c *gin.Context) { c.Header("Access-Control-Allow-Origin", c.Request.Header.Get("Origin")) c.Header("Access-Control-Allow-Credentials", "true") - if c.PostForm("Token") == "" || bson.IsObjectIdHex(c.PostForm("UserId")) == false { + _,err := primitive.ObjectIDFromHex(c.PostForm("UserId")) + if c.PostForm("Token") == "" || err != nil { c.JSON(200, tools.ResponseError{ 1, "Token或者用户id不正确", @@ -82,7 +93,7 @@ func CreateDealyMessage(c *gin.Context) { return } - err := DelayMessage.GlobalDM.AddTaskForAppMessage(c.PostForm("DelayTime"), c.PostForm("UDID"), c.PostForm("Title"), c.PostForm("Content"), c.PostForm("UserId")) + err = DelayMessage.GlobalDM.AddTaskForAppMessage(c.PostForm("DelayTime"), c.PostForm("UDID"), c.PostForm("Title"), c.PostForm("Content"), c.PostForm("UserId")) if err == nil { @@ -114,7 +125,9 @@ func RemoveDealyMessage(c *gin.Context) { c.Header("Access-Control-Allow-Origin", c.Request.Header.Get("Origin")) c.Header("Access-Control-Allow-Credentials", "true") - if c.PostForm("Token") == "" || bson.IsObjectIdHex(c.PostForm("UserId")) == false { + + _,err := primitive.ObjectIDFromHex(c.PostForm("UserId")) + if c.PostForm("Token") == "" || err != nil { c.JSON(200, tools.ResponseError{ 1, "Token或者用户id不正确", diff --git a/API/Icon.go b/API/Icon.go index 34b7515..1bebfe7 100644 --- a/API/Icon.go +++ b/API/Icon.go @@ -3,7 +3,9 @@ package Api import ( "github.com/aarongao/tools" "github.com/gin-gonic/gin" - "gopkg.in/mgo.v2/bson" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo/options" "letu/DB" ) @@ -28,7 +30,8 @@ func IconInfo(c *gin.Context) { } var SIcon *DB.SIcons - DB.CIcons.Find(bson.M{"_id": bson.ObjectIdHex(c.Query("id"))}).One(&SIcon) + objID, _ := primitive.ObjectIDFromHex(c.Query("id")) + DB.CIcons.FindOne(tools.GetContext(), bson.M{"_id": objID}).Decode(&SIcon) c.JSON(200, tools.ResponseSeccess{ 0, @@ -58,20 +61,23 @@ func UpdateIcon(c *gin.Context) { return } - var id bson.ObjectId + var id primitive.ObjectID if pid := c.PostForm("id"); pid == "null" { - id = bson.NewObjectId() + id = primitive.NewObjectID() } else { - id = bson.ObjectIdHex(pid) + id, _ = primitive.ObjectIDFromHex(pid) } - DB.CIcons.UpsertId( - id, + upsert := true + DB.CIcons.FindOneAndUpdate(tools.GetContext(), + bson.M{"_id": id}, bson.M{"$set": bson.M{ "Name": c.PostForm("Name"), "Picture": c.PostForm("Picture"), "ScenicId": ScenicId, - }}, + }}, &options.FindOneAndUpdateOptions{ + Upsert: &upsert, + }, ) c.JSON(200, tools.ResponseSeccess{ @@ -102,8 +108,17 @@ func AllIcons(c *gin.Context) { return } - var SIcons = []*DB.SIcons{} - DB.CIcons.Find(bson.M{"ScenicId": ScenicId}).All(&SIcons) + var SIcons = []DB.SIcons{} + cur, err := DB.CIcons.Find(tools.GetContext(), bson.M{"ScenicId": ScenicId}) + defer cur.Close(tools.GetContext()) + if err == nil { + for cur.Next(tools.GetContext()) { + var e DB.SIcons + cur.Decode(&e) + SIcons = append(SIcons,e) + } + } + c.JSON(200, tools.ResponseSeccess{ 0, diff --git a/API/Investigation.go b/API/Investigation.go index 48aea9e..70f6641 100644 --- a/API/Investigation.go +++ b/API/Investigation.go @@ -4,7 +4,8 @@ import ( "encoding/json" "github.com/aarongao/tools" "github.com/gin-gonic/gin" - "gopkg.in/mgo.v2/bson" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo/options" "letu/DB" "math" "strconv" @@ -27,7 +28,7 @@ func SaveInvestigation(c *gin.Context) { var Data map[string]interface{} json.Unmarshal([]byte(c.PostForm("Data")), &Data) - DB.CInvestigation.Insert(DB.SInvestigation{ + DB.CInvestigation.InsertOne(tools.GetContext(),DB.SInvestigation{ c.PostForm("UserId"), c.PostForm("Mobile"), Data, @@ -53,20 +54,28 @@ func AllInvestigation(c *gin.Context) { c.Header("Access-Control-Allow-Credentials", "true") - total,_ := DB.CComplaint.Find(bson.M{}).Count() - limit,_ := strconv.Atoi(c.Query("Limit")) + total,_ := DB.CComplaint.CountDocuments(tools.GetContext(), bson.M{}) + limit, _ := strconv.ParseInt(c.Query("Limit"),10,64) if limit == 0 { limit = 50 } - currPage, _ := strconv.Atoi(c.Query("Page")) + currPage, _ := strconv.ParseInt(c.Query("Page"),10,64) if currPage == 0 { currPage = 1 } skip := (currPage - 1) * limit var aInvestigation []DB.SInvestigation - DB.CInvestigation.Find(bson.M{}).Limit(limit).Skip(int(skip)).Sort("-_id").All(&aInvestigation) + cur, err := DB.CInvestigation.Find(tools.GetContext(), bson.M{}, &options.FindOptions{Limit: &limit, Skip: &skip, Sort: bson.M{"_id": -1}}) + defer cur.Close(tools.GetContext()) + if err == nil { + for cur.Next(tools.GetContext()) { + var e DB.SInvestigation + cur.Decode(&e) + aInvestigation = append(aInvestigation,e) + } + } c.JSON(200, tools.Page{ 0, total, diff --git a/API/Item.go b/API/Item.go index d9ce563..2684b69 100644 --- a/API/Item.go +++ b/API/Item.go @@ -4,7 +4,9 @@ import ( "encoding/json" "github.com/aarongao/tools" "github.com/gin-gonic/gin" - "gopkg.in/mgo.v2/bson" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo/options" "letu/DB" "strconv" "time" @@ -31,7 +33,8 @@ func ItemInfo(c *gin.Context) { } var SItem DB.SItem - DB.CItem.Find(bson.M{"_id": bson.ObjectIdHex(c.Query("id"))}).One(&SItem) + objID,_ := primitive.ObjectIDFromHex(c.Query("id")) + DB.CItem.FindOne(tools.GetContext(),bson.M{"_id": objID}).Decode(&SItem) c.JSON(200, tools.ResponseSeccess{ 0, @@ -52,7 +55,15 @@ func AllItems(c *gin.Context) { c.Header("Access-Control-Allow-Credentials", "true") var aItems = []DB.SItem{} - DB.CItem.Find(bson.M{}).All(&aItems) + cur, err := DB.CItem.Find(tools.GetContext(), bson.M{}) + defer cur.Close(tools.GetContext()) + if err == nil { + for cur.Next(tools.GetContext()) { + var e DB.SItem + cur.Decode(&e) + aItems = append(aItems,e) + } + } c.JSON(200, aItems) @@ -78,16 +89,18 @@ func UpdateItem(c *gin.Context) { var Picture []string json.Unmarshal([]byte(c.PostForm("Picture")), &Picture) - var id bson.ObjectId + var id primitive.ObjectID if pid := c.PostForm("id"); pid == "null" { - id = bson.NewObjectId() + id = primitive.NewObjectID() } else { - id = bson.ObjectIdHex(pid) + id,_ = primitive.ObjectIDFromHex(pid) } poststate, _ := strconv.Atoi(c.PostForm("State")) - DB.CItem.UpsertId( - id, + + upsert := true + DB.CItem.FindOneAndUpdate(tools.GetContext(), + bson.M{"_id": id}, bson.M{"$set": bson.M{ "Name": c.PostForm("Name"), "SubName": c.PostForm("SubName"), @@ -106,7 +119,9 @@ func UpdateItem(c *gin.Context) { "LocationDescription": c.PostForm("LocationDescription"), "Reminder": c.PostForm("Reminder"), "State": poststate, - }}, + }}, &options.FindOneAndUpdateOptions{ + Upsert: &upsert, + }, ) diff --git a/API/Line.go b/API/Line.go index 7d8c3a1..3bbf618 100644 --- a/API/Line.go +++ b/API/Line.go @@ -4,7 +4,9 @@ import ( "encoding/json" "github.com/aarongao/tools" "github.com/gin-gonic/gin" - "gopkg.in/mgo.v2/bson" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo/options" "letu/DB" ) @@ -29,7 +31,8 @@ func LineInfo(c *gin.Context) { } var SLine DB.SLine - DB.CLine.Find(bson.M{"_id": bson.ObjectIdHex(c.Query("id"))}).One(&SLine) + objID, _ := primitive.ObjectIDFromHex(c.Query("id")) + DB.CLine.FindOne(tools.GetContext(), bson.M{"_id": objID}).Decode(&SLine) c.JSON(200, tools.ResponseSeccess{ 0, @@ -50,7 +53,15 @@ func AllLine(c *gin.Context) { c.Header("Access-Control-Allow-Credentials", "true") var aLine []DB.SLine - DB.CLine.Find(bson.M{}).All(&aLine) + cur, err := DB.CLine.Find(tools.GetContext(), bson.M{}) + defer cur.Close(tools.GetContext()) + if err == nil { + for cur.Next(tools.GetContext()) { + var e DB.SLine + cur.Decode(&e) + aLine = append(aLine,e) + } + } c.JSON(200, aLine) @@ -73,15 +84,16 @@ func UpdateLine(c *gin.Context) { var Annotations []string json.Unmarshal([]byte(c.PostForm("Annotations")), &Annotations) - var id bson.ObjectId + var id primitive.ObjectID if pid := c.PostForm("id"); pid == "null" { - id = bson.NewObjectId() + id = primitive.NewObjectID() } else { - id = bson.ObjectIdHex(pid) + id,_ = primitive.ObjectIDFromHex(pid) } - DB.CLine.UpsertId( - id, + upsert := true + DB.CLine.FindOneAndUpdate(tools.GetContext(), + bson.M{"_id": id}, bson.M{"$set": bson.M{ "Name": c.PostForm("Name"), "SubName": c.PostForm("SubName"), @@ -91,7 +103,9 @@ func UpdateLine(c *gin.Context) { "Distance": c.PostForm("Distance"), "Annotations": Annotations, "Location": Location, - }}, + }}, &options.FindOneAndUpdateOptions{ + Upsert: &upsert, + }, ) c.JSON(200, tools.ResponseSeccess{ diff --git a/API/Scenic.go b/API/Scenic.go index 0b1f92e..4e97680 100644 --- a/API/Scenic.go +++ b/API/Scenic.go @@ -4,7 +4,9 @@ import ( "encoding/json" "github.com/aarongao/tools" "github.com/gin-gonic/gin" - "gopkg.in/mgo.v2/bson" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo/options" "letu/DB" ) @@ -29,7 +31,8 @@ func ScenicInfo(c *gin.Context) { } var Scenic *DB.SScenic - DB.CScenic.Find(bson.M{"_id": bson.ObjectIdHex(c.Query("id"))}).One(&Scenic) + objID,_ := primitive.ObjectIDFromHex(c.Query("id")) + DB.CScenic.FindOne(tools.GetContext(), bson.M{"_id": objID}).Decode(&Scenic) c.JSON(200, tools.ResponseSeccess{ 0, @@ -71,18 +74,19 @@ func UpdateScenic(c *gin.Context) { var VideoList []DB.SVideo json.Unmarshal([]byte(c.PostForm("VideoList")), &VideoList) - var id bson.ObjectId + var id primitive.ObjectID if pid := c.PostForm("id"); pid == "null" { - id = bson.NewObjectId() - + id = primitive.NewObjectID() // 新景区,初始化 initScenic(id.Hex()) } else { - id = bson.ObjectIdHex(pid) + id,_ = primitive.ObjectIDFromHex(pid) } - DB.CScenic.UpsertId( - id, + + upsert := true + DB.CScenic.FindOneAndUpdate(tools.GetContext(), + bson.M{"_id": id}, bson.M{"$set": bson.M{ "Name": c.PostForm("Name"), "Describe": c.PostForm("Describe"), @@ -97,7 +101,9 @@ func UpdateScenic(c *gin.Context) { "ItemScenicPicture": ItemScenicPicture, "ActivityPicture": ActivityPicture, "VideoList": VideoList, - }}, + }}, &options.FindOneAndUpdateOptions{ + Upsert: &upsert, + }, ) c.JSON(200, tools.ResponseSeccess{ @@ -109,23 +115,28 @@ func UpdateScenic(c *gin.Context) { func initScenic(id string) { - DB.CTags.Insert(DB.STag{ + var dba []interface{} + dba = append(dba,DB.STag{ id, "type", "服务设施", - }, DB.STag{ + }) + dba = append(dba,DB.STag{ id, "type", "游乐设施", - }, DB.STag{ + }) + dba = append(dba,DB.STag{ id, "type", "餐饮", - }, DB.STag{ + }) + dba = append(dba,DB.STag{ id, "type", "购物", }) + DB.CTags.InsertMany(tools.GetContext(),dba[1:]) } // @Title 所有景区基础信息 @@ -139,11 +150,19 @@ func AllScenic(c *gin.Context) { c.Header("Access-Control-Allow-Origin", c.Request.Header.Get("Origin")) c.Header("Access-Control-Allow-Credentials", "true") - var Scenic []*DB.SScenic - DB.CScenic.Find(bson.M{}).All(&Scenic) + var Scenic []DB.SScenic + cur, err := DB.CScenic.Find(tools.GetContext(), bson.M{}) + defer cur.Close(tools.GetContext()) + if err == nil { + for cur.Next(tools.GetContext()) { + var e DB.SScenic + cur.Decode(&e) + Scenic = append(Scenic,e) + } + } if Scenic == nil { - Scenic = []*DB.SScenic{} + Scenic = []DB.SScenic{} } c.JSON(200, tools.ResponseSeccess{ diff --git a/API/Shop.go b/API/Shop.go index f63c698..73d8e50 100644 --- a/API/Shop.go +++ b/API/Shop.go @@ -4,7 +4,9 @@ import ( "encoding/json" "github.com/aarongao/tools" "github.com/gin-gonic/gin" - "gopkg.in/mgo.v2/bson" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo/options" "letu/DB" ) @@ -29,7 +31,8 @@ func CommodityInfo(c *gin.Context) { } var SCommodity DB.SCommodity - DB.CCommodity.Find(bson.M{"_id": bson.ObjectIdHex(c.Query("id"))}).One(&SCommodity) + objID, _ := primitive.ObjectIDFromHex(c.Query("id")) + DB.CCommodity.FindOne(tools.GetContext(), bson.M{"_id": objID}).Decode(&SCommodity) c.JSON(200, tools.ResponseSeccess{ 0, @@ -50,7 +53,15 @@ func AllCommodity(c *gin.Context) { c.Header("Access-Control-Allow-Credentials", "true") var aCommoditys []DB.SCommodity - DB.CCommodity.Find(bson.M{}).All(&aCommoditys) + cur, err := DB.CCommodity.Find(tools.GetContext(), bson.M{}) + defer cur.Close(tools.GetContext()) + if err == nil { + for cur.Next(tools.GetContext()) { + var e DB.SCommodity + cur.Decode(&e) + aCommoditys = append(aCommoditys,e) + } + } c.JSON(200, aCommoditys) @@ -76,15 +87,17 @@ func UpdateCommodity(c *gin.Context) { //var Location DB.SLocation //json.Unmarshal([]byte(c.PostForm("Location")), &Location) - var id bson.ObjectId + + var id primitive.ObjectID if pid := c.PostForm("id"); pid == "null" { - id = bson.NewObjectId() + id = primitive.NewObjectID() } else { - id = bson.ObjectIdHex(pid) + id,_ = primitive.ObjectIDFromHex(pid) } - DB.CCommodity.UpsertId( - id, + upsert := true + DB.CCommodity.FindOneAndUpdate(tools.GetContext(), + bson.M{"_id": id}, bson.M{"$set": bson.M{ "Name": c.PostForm("Name"), "Price": c.PostForm("Price"), @@ -93,7 +106,9 @@ func UpdateCommodity(c *gin.Context) { "TopPhoto": TopPhoto, "ItemId": c.PostForm("ItemId"), "Images": Picture, - }}, + }}, &options.FindOneAndUpdateOptions{ + Upsert: &upsert, + }, ) c.JSON(200, tools.ResponseSeccess{ diff --git a/API/Sms.go b/API/Sms.go index ee24787..4928828 100644 --- a/API/Sms.go +++ b/API/Sms.go @@ -75,7 +75,7 @@ func Send(c *gin.Context) { json.Unmarshal([]byte(c.PostForm("Location")), &Location) //go func(res *dysmsapi.SendSmsResponse) { - DB.CSystemLog.Insert(DB.SSystemLog{ + DB.CSystemLog.InsertOne(tools.GetContext(),DB.SSystemLog{ "", "", c.PostForm("Mobile"), diff --git a/API/Tag.go b/API/Tag.go index 62e5aec..dfb01e9 100644 --- a/API/Tag.go +++ b/API/Tag.go @@ -3,7 +3,7 @@ package Api import ( "github.com/aarongao/tools" "github.com/gin-gonic/gin" - "gopkg.in/mgo.v2/bson" + "go.mongodb.org/mongo-driver/bson" "letu/DB" "letu/Lib/LeYouTu" "time" @@ -26,11 +26,21 @@ func AllTag(c *gin.Context) { return } - var Stags []*DB.STag - DB.CTags.Find(bson.M{"ScenicId": ScenicId}).All(&Stags) + var Stags []DB.STag + cur, err := DB.CTags.Find(tools.GetContext(), bson.M{"ScenicId": ScenicId}) + defer cur.Close(tools.GetContext()) + if err == nil { + for cur.Next(tools.GetContext()) { + var e DB.STag + cur.Decode(&e) + Stags = append(Stags,e) + } + } + + if Stags == nil { - Stags = []*DB.STag{} + Stags = []DB.STag{} } c.JSON(200, tools.ResponseSeccess{ @@ -67,11 +77,19 @@ func AllTagGroup(c *gin.Context) { return } - var Stags []*DB.STag - DB.CTags.Find(bson.M{"ScenicId": ScenicId}).All(&Stags) + var Stags []DB.STag + cur, err := DB.CTags.Find(tools.GetContext(), bson.M{"ScenicId": ScenicId}) + defer cur.Close(tools.GetContext()) + if err == nil { + for cur.Next(tools.GetContext()) { + var e DB.STag + cur.Decode(&e) + Stags = append(Stags,e) + } + } if Stags == nil { - Stags = []*DB.STag{} + Stags = []DB.STag{} } Group := make(map[string][]string) @@ -141,7 +159,7 @@ func CreateTag(c *gin.Context) { return } - DB.CTags.Insert(DB.STag{ + DB.CTags.InsertOne(tools.GetContext(),DB.STag{ ScenicId, c.PostForm("TagGroup"), c.PostForm("TagName"), @@ -204,7 +222,7 @@ func RemoveTag(c *gin.Context) { return } - DB.CTags.Remove(bson.M{"ScenicId": ScenicId,"Name":c.PostForm("TagName"),"Type":c.PostForm("TagGroup")}) + DB.CTags.DeleteOne(tools.GetContext(), bson.M{"ScenicId": ScenicId,"Name":c.PostForm("TagName"),"Type":c.PostForm("TagGroup")}) DB.Redis.Delete("Tags_" + ScenicId) println("清楚缓存Tags") diff --git a/API/TopMenus.go b/API/TopMenus.go index 3c70b77..2707b25 100644 --- a/API/TopMenus.go +++ b/API/TopMenus.go @@ -4,7 +4,9 @@ import ( "encoding/json" "github.com/aarongao/tools" "github.com/gin-gonic/gin" - "gopkg.in/mgo.v2/bson" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo/options" "letu/DB" "letu/Lib/LeYouTu" ) @@ -25,11 +27,19 @@ func AllTopMenus(c *gin.Context) { return } - var STopMenus []*DB.STopMenus - DB.CTopMenus.Find(bson.M{"ScenicId": ScenicId}).All(&STopMenus) + var STopMenus []DB.STopMenus + cur, err := DB.CTopMenus.Find(tools.GetContext(), bson.M{"ScenicId": ScenicId}) + defer cur.Close(tools.GetContext()) + if err == nil { + for cur.Next(tools.GetContext()) { + var e DB.STopMenus + cur.Decode(&e) + STopMenus = append(STopMenus,e) + } + } if STopMenus == nil { - STopMenus = []*DB.STopMenus{} + STopMenus = []DB.STopMenus{} } c.JSON(200, tools.ResponseSeccess{ @@ -66,20 +76,23 @@ func UpdateTopMenus(c *gin.Context) { var Tags []string json.Unmarshal([]byte(c.PostForm("Tags")), &Tags) - var id bson.ObjectId + var id primitive.ObjectID if pid := c.PostForm("id"); pid == "null" { - id = bson.NewObjectId() + id = primitive.NewObjectID() } else { - id = bson.ObjectIdHex(pid) + id,_ = primitive.ObjectIDFromHex(pid) } - DB.CTopMenus.UpsertId( - id, + upsert := true + DB.CTopMenus.FindOneAndUpdate(tools.GetContext(), + bson.M{"_id": id}, bson.M{"$set": bson.M{ "ScenicId": ScenicId, "Title": c.PostForm("Title"), "Tags": Tags, - }}, + }}, &options.FindOneAndUpdateOptions{ + Upsert: &upsert, + }, ) c.JSON(200, tools.ResponseSeccess{ diff --git a/API/Trajectory.go b/API/Trajectory.go index a6a7f01..623a352 100644 --- a/API/Trajectory.go +++ b/API/Trajectory.go @@ -24,7 +24,7 @@ func SaveTrajectory(c *gin.Context) { var Location DB.SLocation json.Unmarshal([]byte(c.PostForm("Location")), &Location) - DB.CTrajectory.Insert(DB.STrajectory{ + DB.CTrajectory.InsertOne(tools.GetContext(),DB.STrajectory{ c.PostForm("UserId"), Location, time.Now().Unix(), diff --git a/API/User.go b/API/User.go index f47dd2f..c105311 100644 --- a/API/User.go +++ b/API/User.go @@ -5,7 +5,9 @@ import ( "encoding/hex" "github.com/aarongao/tools" "github.com/gin-gonic/gin" - "gopkg.in/mgo.v2/bson" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo/options" "letu/DB" "letu/Lib/Token" "regexp" @@ -63,11 +65,11 @@ func LoginUser(c *gin.Context) { var User *DB.SMember if cacheCode == c.PostForm("Code") { selected["Mobile"] = c.PostForm("Mobile") - DB.CMember.Find(selected).One(&User) + DB.CMember.FindOne(tools.GetContext(), selected).Decode(&User) // 验证码匹配,但手机号不存在 if User == nil { - objectID := bson.NewObjectId() + objectID := primitive.NewObjectID() User := DB.SMember{ &objectID, "", @@ -88,7 +90,7 @@ func LoginUser(c *gin.Context) { c.Request.Header.Get("DeviceToken"), }, } - DB.CMember.Insert(User) + DB.CMember.InsertOne(tools.GetContext(),User) } } else { @@ -142,7 +144,8 @@ func RegisterDevice(c *gin.Context) { return } - DB.CDevice.Upsert( + upsert := true + DB.CDevice.FindOneAndUpdate(tools.GetContext(), bson.M{"DeviceId":c.Request.Header.Get("DeviceId")}, bson.M{"$set": bson.M{ "Mac":c.Request.Header.Get("Mac"), @@ -152,7 +155,9 @@ func RegisterDevice(c *gin.Context) { "SystemModel":c.Request.Header.Get("SystemModel"), "AppVersion":c.Request.Header.Get("AppVersion"), "DeviceToken":c.Request.Header.Get("DeviceToken"), - }}, + }}, &options.FindOneAndUpdateOptions{ + Upsert: &upsert, + }, ) c.JSON(200, tools.ResponseSeccess{ @@ -175,7 +180,8 @@ func UserInfo(c *gin.Context) { c.Header("Access-Control-Allow-Origin", c.Request.Header.Get("Origin")) c.Header("Access-Control-Allow-Credentials", "true") - if c.Query("Token") == "" || bson.IsObjectIdHex(c.Query("id")) == false { + objID,err := primitive.ObjectIDFromHex(c.Query("id")) + if c.Query("Token") == "" || err!=nil { c.JSON(200, tools.ResponseError{ 1, "Token或者用户id不正确", @@ -192,7 +198,7 @@ func UserInfo(c *gin.Context) { } var User DB.SMember - DB.CMember.Find(bson.M{"_id": bson.ObjectIdHex(c.Query("id"))}).One(&User) + DB.CMember.FindOne(tools.GetContext(), bson.M{"_id": objID}).Decode(&User) User.Device = DB.SDevice{} c.JSON(200, tools.ResponseSeccess{ @@ -215,7 +221,8 @@ func CheckToken(c *gin.Context) { c.Header("Access-Control-Allow-Origin", c.Request.Header.Get("Origin")) c.Header("Access-Control-Allow-Credentials", "true") - if c.PostForm("Token") == "" || bson.IsObjectIdHex(c.PostForm("id")) == false { + _,err := primitive.ObjectIDFromHex(c.PostForm("id")) + if c.PostForm("Token") == "" || err != nil { c.JSON(200, tools.ResponseError{ 1, "Token或者用户id不正确", @@ -257,7 +264,8 @@ func UpdateUser(c *gin.Context) { c.Header("Access-Control-Allow-Origin", c.Request.Header.Get("Origin")) c.Header("Access-Control-Allow-Credentials", "true") - if c.PostForm("Token") == "" || bson.IsObjectIdHex(c.PostForm("id")) == false { + _,err := primitive.ObjectIDFromHex(c.PostForm("id")) + if c.PostForm("Token") == "" || err != nil { c.JSON(200, tools.ResponseError{ 1, "Token或者用户id不正确", @@ -309,8 +317,9 @@ func UpdateUser(c *gin.Context) { return } - err := DB.CMember.Update( - bson.M{"_id": bson.ObjectIdHex(c.PostForm("id"))}, + objID,_ := primitive.ObjectIDFromHex(c.PostForm("id")) + _, err = DB.CMember.UpdateOne(tools.GetContext(), + bson.M{"_id": objID}, bson.M{"$set": bson.M{ "Birthday": c.PostForm("Birthday"), "FullName": c.PostForm("FullName"), @@ -321,7 +330,8 @@ func UpdateUser(c *gin.Context) { if err == nil { var User *DB.SMember - DB.CMember.Find(bson.M{"_id": bson.ObjectIdHex(c.PostForm("id"))}).One(&User) + objID,_ := primitive.ObjectIDFromHex(c.PostForm("id")) + DB.CMember.FindOne(tools.GetContext(), bson.M{"_id": objID}).Decode(&User) c.JSON(200, tools.ResponseSeccess{ 0, @@ -350,7 +360,8 @@ func RemoveUser(c *gin.Context) { c.Header("Access-Control-Allow-Origin", c.Request.Header.Get("Origin")) c.Header("Access-Control-Allow-Credentials", "true") - if c.PostForm("Token") == "" || bson.IsObjectIdHex(c.PostForm("id")) == false { + objID,err := primitive.ObjectIDFromHex(c.PostForm("id")) + if c.PostForm("Token") == "" || err != nil { c.JSON(200, tools.ResponseError{ 1, "Token或者用户id不正确", @@ -366,11 +377,10 @@ func RemoveUser(c *gin.Context) { return } - - err := DB.CMember.Remove(bson.M{"_id": bson.ObjectIdHex(c.PostForm("id"))}) + _, err = DB.CMember.DeleteOne(tools.GetContext(), bson.M{"_id": objID}) if err == nil { - + c.JSON(200, tools.ResponseSeccess{ 0, "ok", diff --git a/API/UserLog.go b/API/UserLog.go index c4ce8bd..f0d6af1 100644 --- a/API/UserLog.go +++ b/API/UserLog.go @@ -4,8 +4,11 @@ import ( "encoding/json" "github.com/aarongao/tools" "github.com/gin-gonic/gin" - "gopkg.in/mgo.v2/bson" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo/options" "letu/DB" + "math" + "strconv" "time" ) @@ -46,7 +49,7 @@ func UserLog(c *gin.Context) { var Location DB.SLocation json.Unmarshal([]byte(c.PostForm("Location")), &Location) - DB.CUserLog.Insert(DB.SUserLog{ + DB.CUserLog.InsertOne(tools.GetContext(),DB.SUserLog{ c.PostForm("Type"), c.PostForm("SubType"), c.PostForm("ScenicId"), @@ -69,7 +72,8 @@ func UserLog(c *gin.Context) { }, }) - DB.CDevice.Upsert( + upsert := true + DB.CDevice.FindOneAndUpdate(tools.GetContext(), bson.M{"DeviceId": c.Request.Header.Get("DeviceId")}, bson.M{"$set": bson.M{ "Mac": c.Request.Header.Get("Mac"), @@ -79,7 +83,9 @@ func UserLog(c *gin.Context) { "SystemModel": c.Request.Header.Get("SystemModel"), "AppVersion": c.Request.Header.Get("AppVersion"), "DeviceToken": c.Request.Header.Get("DeviceToken"), - }}, + }}, &options.FindOneAndUpdateOptions{ + Upsert: &upsert, + }, ) c.JSON(200, tools.ResponseSeccess{ @@ -88,3 +94,51 @@ func UserLog(c *gin.Context) { }) } + + +// @Title 查询所有用户行为 +// @Description 查询所有用户行为 +// @Accept json +// @Produce json +// @Param Page 1 int true "当前第几页" +// @Success 200 {object} tools.ResponseSeccess "{"errcode":0,"total":1,"currpage":1,"totalpages":1,"prepage":20,"result":}" +// @Failure 500 {object} tools.ResponseError "{"errcode":1,"errmsg":"错误原因"}" +// @Router /AllUserLog? [get] +func AllUserLog(c *gin.Context) { + c.Header("Access-Control-Allow-Origin", c.Request.Header.Get("Origin")) + c.Header("Access-Control-Allow-Credentials", "true") + + + total,_ := DB.CUserLog.CountDocuments(tools.GetContext(), bson.M{}) + limit, _ := strconv.ParseInt(c.Query("Limit"),10,64) + if limit == 0 { + limit = 50 + } + currPage, _ := strconv.ParseInt(c.Query("Page"),10,64) + if currPage == 0 { + currPage = 1 + } + skip := (currPage - 1) * limit + + var aUserLog []DB.SUserLog + cur, err := DB.CUserLog.Find(tools.GetContext(), bson.M{}, &options.FindOptions{Limit: &limit, Skip: &skip, Sort: bson.M{"_id": -1}}) + defer cur.Close(tools.GetContext()) + if err == nil { + for cur.Next(tools.GetContext()) { + var e DB.SUserLog + cur.Decode(&e) + aUserLog = append(aUserLog,e) + } + } + + + c.JSON(200, tools.Page{ + 0, + total, + currPage, + int(math.Ceil(float64(total) / float64(limit))), + limit, + aUserLog, + }) + +} \ No newline at end of file diff --git a/Bin/Monitor.go b/Bin/Monitor.go new file mode 100644 index 0000000..58ffc93 --- /dev/null +++ b/Bin/Monitor.go @@ -0,0 +1,70 @@ +package main + +import ( + "encoding/json" + "github.com/aarongao/tools" + "github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi" + "time" +) + +var lastState = 0 + +func main() { + + for { + time.Sleep(30 * time.Second) + httpState, body, error := tools.GET("http://leyoutu.st-i.com.cn/AllScenic") + if httpState == 200 && error == nil { + + oBody := tools.ResponseSeccess{} + json.Unmarshal([]byte(body), &oBody) + + rlen := len(oBody.Result.([]interface{})) + if oBody.ErrCode != 0 || rlen == 0 { + sms(1) + } else { + sms(2) + } + } else { + + sms(1) + } + + } + +} + +func sms(state int) { + + stateString := "" + if state == 1{ + stateString = "Fail" + } + if state == 2{ + stateString = "Success" + } + println("state:",stateString) + + + if lastState == 0 { + lastState = state + } + + if lastState != state{ + + lastState = state + + client, err := dysmsapi.NewClientWithAccessKey("cn-hangzhou", "LTAI4FdQeNMQXRU6u5J3EFQc", "PwvyF5rRNBWLDya41WrCpvENevYZGi") + request := dysmsapi.CreateSendSmsRequest() + request.Scheme = "https" + request.PhoneNumbers = "18616619599" + request.SignName = "乐游图" + request.TemplateCode = "SMS_182595013" + request.TemplateParam = "{\"code\":\"" + stateString +"\"}" + response, err := client.SendSms(request) + if err != nil { + println(err.Error()) + } + println("SMS:", response.Code) + } +} diff --git a/DB/db.go b/DB/db.go index b58f3d1..14987ba 100644 --- a/DB/db.go +++ b/DB/db.go @@ -1,56 +1,55 @@ package DB import ( - "gopkg.in/mgo.v2" - "gopkg.in/mgo.v2/bson" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo" "letu/Lib/Cache" ) var Redis *Cache.Redis -var DBSession *mgo.Session -var CItem *mgo.Collection //所有游玩项目内容 -var CComplaint *mgo.Collection //投诉 -var CInvestigation *mgo.Collection //调查 -var CMember *mgo.Collection //会员 -var CCommodity *mgo.Collection //商城 -var CTags *mgo.Collection //标签 -var CScenic *mgo.Collection //景区 -var CLine *mgo.Collection //推荐线路 -var CUserLog *mgo.Collection //用户行为记录 -var CSystemLog *mgo.Collection //操作记录 -var CTrajectory *mgo.Collection //移动轨迹 -var CIcons *mgo.Collection //图标信息 -var CTopMenus *mgo.Collection //菜单 -var CDevice *mgo.Collection //设备清单 -var DB *mgo.Database +var CItem *mongo.Collection //所有游玩项目内容 +var CComplaint *mongo.Collection //投诉 +var CInvestigation *mongo.Collection //调查 +var CMember *mongo.Collection //会员 +var CCommodity *mongo.Collection //商城 +var CTags *mongo.Collection //标签 +var CScenic *mongo.Collection //景区 +var CLine *mongo.Collection //推荐线路 +var CUserLog *mongo.Collection //用户行为记录 +var CSystemLog *mongo.Collection //操作记录 +var CTrajectory *mongo.Collection //移动轨迹 +var CIcons *mongo.Collection //图标信息 +var CTopMenus *mongo.Collection //菜单 +var CDevice *mongo.Collection //设备清单 +var DB *mongo.Database type SItem struct { - Id *bson.ObjectId `bson:"_id" json:"Id" valid:"required"` - Name string `bson:"Name" json:"Name"` - SubName string `bson:"SubName" json:"SubName"` - Location SLocation `bson:"Location" json:"Location"` - Tags []STag `bson:"Tags" json:"Tags"` - Icon string `bson:"Icon" json:"Icon"` - LimitHeight string `bson:"LimitHeight" json:"LimitHeight"` //限高 - PlayDuration string `bson:"PlayDuration" json:"PlayDuration"` //游玩时长 - SceneTime string `bson:"SceneTime" json:"SceneTime"` //场次时间 - Picture []string `bson:"Picture" json:"Picture"` - Voice string `bson:"Voice" json:"Voice"` //音频 - Tel string `bson:"Tel" json:"Tel"` - AverageConsumption string `bson:"AverageConsumption" json:"AverageConsumption"` //人均消费 - Menu string `bson:"Menu" json:"Menu"` //目录 - Time string `bson:"Time" json:"Time"` - OpenHours string `bson:"OpenHours" json:"OpenHours"` //开放时间 - LocationDescription string `bson:"LocationDescription" json:"LocationDescription"` //位置描述 - Reminder string `bson:"Reminder" json:"Reminder"` //温馨提示 - State int `bson:"State" json:"State"` // 运行状态0=正常1=停运 + Id *primitive.ObjectID `bson:"_id" json:"Id" valid:"required"` + Name string `bson:"Name" json:"Name"` + SubName string `bson:"SubName" json:"SubName"` + Location SLocation `bson:"Location" json:"Location"` + Tags []STag `bson:"Tags" json:"Tags"` + Icon string `bson:"Icon" json:"Icon"` + LimitHeight string `bson:"LimitHeight" json:"LimitHeight"` //限高 + PlayDuration string `bson:"PlayDuration" json:"PlayDuration"` //游玩时长 + SceneTime string `bson:"SceneTime" json:"SceneTime"` //场次时间 + Picture []string `bson:"Picture" json:"Picture"` + Voice string `bson:"Voice" json:"Voice"` //音频 + Tel string `bson:"Tel" json:"Tel"` + AverageConsumption string `bson:"AverageConsumption" json:"AverageConsumption"` //人均消费 + Menu string `bson:"Menu" json:"Menu"` //目录 + Time string `bson:"Time" json:"Time"` + OpenHours string `bson:"OpenHours" json:"OpenHours"` //开放时间 + LocationDescription string `bson:"LocationDescription" json:"LocationDescription"` //位置描述 + Reminder string `bson:"Reminder" json:"Reminder"` //温馨提示 + State int `bson:"State" json:"State"` // 运行状态0=正常1=停运 } type SIcons struct { - Id *bson.ObjectId `bson:"_id" json:"Id" valid:"required"` - ScenicId string `bson:"ScenicId" json:"ScenicId"` - Name string `bson:"Name" json:"Name"` - Picture string `bson:"Picture" json:"Picture"` + Id *primitive.ObjectID `bson:"_id" json:"Id" valid:"required"` + ScenicId string `bson:"ScenicId" json:"ScenicId"` + Name string `bson:"Name" json:"Name"` + Picture string `bson:"Picture" json:"Picture"` } type STrajectory struct { UserId string `bson:"UserId" json:"UserId"` // 用户ID @@ -62,10 +61,10 @@ type SLocation struct { Longitude float64 `bson:"Longitude" json:"Longitude"` //经度 } type STopMenus struct { - Id *bson.ObjectId `bson:"_id" json:"Id" valid:"required"` - ScenicId string `bson:"ScenicId" json:"ScenicId"` - Title string `bson:"Title" json:"Title"` //菜单标题 - Tags []string `bson:"Tags" json:"Tags"` //标签 + Id *primitive.ObjectID `bson:"_id" json:"Id" valid:"required"` + ScenicId string `bson:"ScenicId" json:"ScenicId"` + Title string `bson:"Title" json:"Title"` //菜单标题 + Tags []string `bson:"Tags" json:"Tags"` //标签 } type SDevice struct { @@ -104,25 +103,25 @@ type SSystemLog struct { Error interface{} `bson:"Error" json:"Error"` //错误信息 } type SCommodity struct { - Id *bson.ObjectId `bson:"_id" json:"Id" valid:"required"` - Name string `bson:"Name" json:"Name"` - Price string `bson:"Price" json:"Price"` - ShopName string `bson:"ShopName" json:"ShopName"` - ItemId string `bson:"ItemId" json:"ItemId"` //项目id - KvPhoto string `bson:"KvPhoto" json:"KvPhoto"` //用于列表页的图片 - TopPhoto []SPicture `bson:"TopPhoto" json:"TopPhoto"` //详情页最上面的轮播图 - Images []string `bson:"Images" json:"Images"` //详情页下面的产品详细图 + Id *primitive.ObjectID `bson:"_id" json:"Id" valid:"required"` + Name string `bson:"Name" json:"Name"` + Price string `bson:"Price" json:"Price"` + ShopName string `bson:"ShopName" json:"ShopName"` + ItemId string `bson:"ItemId" json:"ItemId"` //项目id + KvPhoto string `bson:"KvPhoto" json:"KvPhoto"` //用于列表页的图片 + TopPhoto []SPicture `bson:"TopPhoto" json:"TopPhoto"` //详情页最上面的轮播图 + Images []string `bson:"Images" json:"Images"` //详情页下面的产品详细图 } type SLine struct { - Id *bson.ObjectId `bson:"_id" json:"Id" valid:"required"` - Name string `bson:"Name" json:"Name"` - SubName string `bson:"SubName" json:"SubName"` //游玩时长 - Location []SLocation `bson:"Location" json:"Location"` //线路点坐标 - PlayDuration string `bson:"PlayDuration" json:"PlayDuration"` - Suitable string `bson:"Suitable" json:"Suitable"` //适合人群 - Content string `bson:"Content" json:"Content"` - Distance string `bson:"Distance" json:"Distance"` // 距离 - Annotations []string `bson:"Annotations" json:"Annotations"` //需要点亮的设施id + Id *primitive.ObjectID `bson:"_id" json:"Id" valid:"required"` + Name string `bson:"Name" json:"Name"` + SubName string `bson:"SubName" json:"SubName"` //游玩时长 + Location []SLocation `bson:"Location" json:"Location"` //线路点坐标 + PlayDuration string `bson:"PlayDuration" json:"PlayDuration"` + Suitable string `bson:"Suitable" json:"Suitable"` //适合人群 + Content string `bson:"Content" json:"Content"` + Distance string `bson:"Distance" json:"Distance"` // 距离 + Annotations []string `bson:"Annotations" json:"Annotations"` //需要点亮的设施id } type SComplaint struct { @@ -133,6 +132,8 @@ type SComplaint struct { Sex string `bson:"Sex" json:"Sex"` Content string `bson:"Content" json:"Content"` Image []string `bson:"Image" json:"Image"` + State string `bson:"State" json:"State"` // 处理状态(未处理,已处理) + DateTime int64 `bson:"DateTime" json:"DateTime"` //时间戳 } type SInvestigation struct { @@ -141,15 +142,15 @@ type SInvestigation struct { Data interface{} `bson:"Data" json:"Data"` } type SMember struct { - Id *bson.ObjectId `bson:"_id" json:"Id" valid:"required"` - Password string `bson:"Password" json:"Password"` - Birthday string `bson:"Birthday" json:"Birthday"` - FullName string `bson:"FullName" json:"FullName"` - Mobile string `bson:"Mobile" json:"Mobile"` - Openid string `bson:"Openid" json:"Openid"` - Token string `bson:"Token" json:"Token"` - Sex string `bson:"Sex" json:"Sex"` - Device SDevice `bson:"Device" json:"Device"` //设备信息 + Id *primitive.ObjectID `bson:"_id" json:"Id" valid:"required"` + Password string `bson:"Password" json:"Password"` + Birthday string `bson:"Birthday" json:"Birthday"` + FullName string `bson:"FullName" json:"FullName"` + Mobile string `bson:"Mobile" json:"Mobile"` + Openid string `bson:"Openid" json:"Openid"` + Token string `bson:"Token" json:"Token"` + Sex string `bson:"Sex" json:"Sex"` + Device SDevice `bson:"Device" json:"Device"` //设备信息 } type STag struct { @@ -169,18 +170,18 @@ type SVideo struct { Title string `bson:"Title" json:"Title"` // 标题 } type SScenic struct { - Id *bson.ObjectId `bson:"_id" json:"Id" valid:"required"` - Name string `bson:"Name" json:"Name"` - Describe string `bson:"Describe" json:"Describe"` - OpenHours string `bson:"OpenHours" json:"OpenHours"` //营业时间 - Mobile string `bson:"Mobile" json:"Mobile"` - Address string `bson:"Address" json:"Address"` - InvestigationUrl string `bson:"InvestigationUrl" json:"InvestigationUrl"` //问券调查的url地址 - Location SLocation `bson:"Location" json:"Location"` - Picture []SPicture `bson:"Picture" json:"Picture"` - ShopAdPicture []SPicture `bson:"ShopAdPicture" json:"ShopAdPicture"` //商城列表页图片 - ItemScenicPicture []SPicture `bson:"ItemScenicPicture" json:"ItemScenicPicture"` //项目场次照片 - ActivityPicture []SPicture `bson:"ActivityPicture" json:"ActivityPicture"` //活动照片 - VideoList []SVideo `bson:"VideoList" json:"VideoList"` - RangeLocation []SLocation `bson:"RangeLocation" json:"RangeLocation"` //景区范围 + Id *primitive.ObjectID `bson:"_id" json:"Id" valid:"required"` + Name string `bson:"Name" json:"Name"` + Describe string `bson:"Describe" json:"Describe"` + OpenHours string `bson:"OpenHours" json:"OpenHours"` //营业时间 + Mobile string `bson:"Mobile" json:"Mobile"` + Address string `bson:"Address" json:"Address"` + InvestigationUrl string `bson:"InvestigationUrl" json:"InvestigationUrl"` //问券调查的url地址 + Location SLocation `bson:"Location" json:"Location"` + Picture []SPicture `bson:"Picture" json:"Picture"` + ShopAdPicture []SPicture `bson:"ShopAdPicture" json:"ShopAdPicture"` //商城列表页图片 + ItemScenicPicture []SPicture `bson:"ItemScenicPicture" json:"ItemScenicPicture"` //项目场次照片 + ActivityPicture []SPicture `bson:"ActivityPicture" json:"ActivityPicture"` //活动照片 + VideoList []SVideo `bson:"VideoList" json:"VideoList"` + RangeLocation []SLocation `bson:"RangeLocation" json:"RangeLocation"` //景区范围 } diff --git a/Lib/DelayMessage/delaymessage.go b/Lib/DelayMessage/delaymessage.go index 6868905..c599eae 100644 --- a/Lib/DelayMessage/delaymessage.go +++ b/Lib/DelayMessage/delaymessage.go @@ -1,11 +1,14 @@ package DelayMessage import ( + "context" "encoding/json" "fmt" + "github.com/aarongao/tools" "github.com/pkg/errors" - "gopkg.in/mgo.v2" - "gopkg.in/mgo.v2/bson" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/bson" "io/ioutil" "net/http" "strconv" @@ -14,12 +17,12 @@ import ( ) // 延迟消息 -var CDelayMessage *mgo.Collection -var CDelayErrorLog *mgo.Collection +var CDelayMessage *mongo.Collection +var CDelayErrorLog *mongo.Collection var GlobalDM *DelayMessage type Message struct { - Id *bson.ObjectId `bson:"_id" json:"_id"` + Id *primitive.ObjectID `bson:"_id" json:"_id"` //延时时间 DelayTime int64 //callbackUrl @@ -50,10 +53,11 @@ func (dm *DelayMessage) AddTaskForGetUrl(delayTime string, userid string, callba return errors.New("callbackUrl error...") } - objectID := bson.NewObjectId() + objectID := primitive.NewObjectID() _Message := &Message{&objectID, i64Time, callbackUrl, 0, 0, "", "", "", userid} - CDelayMessage.Insert(_Message) + ctx, _ := context.WithTimeout(context.Background(), 5*time.Second) + CDelayMessage.InsertOne(ctx, _Message) //添加任务 //iDelayTIme = 3 @@ -87,10 +91,10 @@ func (dm *DelayMessage) AddTaskForAppMessage(delayTime string, udid string, titl return errors.New("userid error...") } - objectID := bson.NewObjectId() + objectID := primitive.NewObjectID() _Message := &Message{&objectID, i64Time, "", 0, 1, title, content, udid, userid} - CDelayMessage.Insert(_Message) + CDelayMessage.InsertOne(tools.GetContext(), _Message) //添加任务 //iDelayTIme = 3 @@ -110,9 +114,10 @@ func (dm *DelayMessage) DelTaskForId(id string) { } }() - CDelayMessage.Remove(bson.M{"_id": bson.ObjectIdHex(id)}) + objID, _ := primitive.ObjectIDFromHex(id) + CDelayMessage.DeleteOne(tools.GetContext(), bson.M{"_id": objID}) i := dm.DelTask(id) - println("删除定时任务:",strconv.Itoa(i)) + println("删除定时任务:", strconv.Itoa(i)) } func (dm *DelayMessage) Show() { @@ -129,7 +134,7 @@ func (dm *DelayMessage) Show() { } -func Callback(key *bson.ObjectId, message *Message) { +func Callback(key *primitive.ObjectID, message *Message) { var body string var err error @@ -156,7 +161,7 @@ func Callback(key *bson.ObjectId, message *Message) { json, _ := json.Marshal(message) if body != "ok" { - CDelayMessage.Remove(bson.M{"_id": *key}) + CDelayMessage.DeleteOne(tools.GetContext(), bson.M{"_id": *key}) fmt.Println("完成任务:", string(json)) } else { @@ -164,7 +169,7 @@ func Callback(key *bson.ObjectId, message *Message) { //if message.Fail == 3 { // fmt.Println(color.Red("放弃任务:"), message.CallbackUrl) // CDelayMessage.Remove(bson.M{"_id": *key}) - // dbErrorLog.Insert(message) + // dbErrorLog.InsertOne(tools.GetContext(),message) //} else { // fmt.Println("重新添加任务:", message) // dm.AddTask(time.Now().Add(time.Second*10), key, callback, message) @@ -172,7 +177,7 @@ func Callback(key *bson.ObjectId, message *Message) { fmt.Println("放弃任务:", string(json)) //CDelayMessage.Remove(bson.M{"_id": *key}) - CDelayErrorLog.Insert(message) + CDelayErrorLog.InsertOne(tools.GetContext(), message) } } @@ -182,13 +187,13 @@ type DelayMessage struct { curIndex int //环形槽 sync.RWMutex - slots [3600]map[*bson.ObjectId]*Task + slots [3600]map[*primitive.ObjectID]*Task //启动时间 startTime time.Time } //执行的任务函数 -type TaskFunc func(key *bson.ObjectId, message *Message) +type TaskFunc func(key *primitive.ObjectID, message *Message) //任务 type Task struct { @@ -206,7 +211,7 @@ func NewDelayMessage() *DelayMessage { startTime: time.Now(), } for i := 0; i < 3600; i++ { - dm.slots[i] = make(map[*bson.ObjectId]*Task) + dm.slots[i] = make(map[*primitive.ObjectID]*Task) } return dm } diff --git a/main.go b/main.go index e6cba24..97c7b68 100644 --- a/main.go +++ b/main.go @@ -3,14 +3,17 @@ package main import ( "encoding/json" "github.com/aarongao/tools" + "github.com/davecgh/go-spew/spew" "github.com/gin-gonic/gin" - "gopkg.in/mgo.v2" - "gopkg.in/mgo.v2/bson" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" "letu/Api" "letu/Config" "letu/DB" "letu/Lib/Cache" "letu/Lib/DelayMessage" + "log" "os" "time" ) @@ -22,7 +25,6 @@ func main() { // 读取配置文件 dir, _ := os.Getwd() - //println(dir) file, _ := os.Open(dir + "/Config/config.json") defer file.Close() decoder := json.NewDecoder(file) @@ -31,49 +33,57 @@ func main() { tools.CheckError(err) // 连接数据库 - DB.DBSession, err = mgo.Dial(conf.DbPath) + // Set client options + clientOptions := options.Client().ApplyURI("mongodb://" + conf.DbPath) + clientOptions.SetLocalThreshold(3 * time.Second) //只使用与mongo操作耗时小于3秒的 + clientOptions.SetMaxConnIdleTime(5 * time.Second) //指定连接可以保持空闲的最大毫秒数 + clientOptions.SetMaxPoolSize(4096) //使用最大的连接数 + + // Connect to MongoDB + client, err := mongo.Connect(tools.GetContext(), clientOptions) + if err != nil { + log.Fatal(err) + } + + // Check the connection + err = client.Ping(tools.GetContext(), nil) + if err != nil { + log.Fatal(err) + } + log.Println("Connected to MongoDB!") - defer DB.DBSession.Close() + //获取文档集 + DB.DB = client.Database("LeYouTu") + //DB.DB.Login(conf.DbUser, conf.DbPassword) + + DB.CItem = DB.DB.Collection("Item") + DB.CComplaint = DB.DB.Collection("Complaint") + DB.CInvestigation = DB.DB.Collection("Investigation") + DB.CMember = DB.DB.Collection("Member") + DB.CCommodity = DB.DB.Collection("Commodity") + DB.CTags = DB.DB.Collection("Tags") + DB.CScenic = DB.DB.Collection("Scenic") + DB.CLine = DB.DB.Collection("Line") + DB.CUserLog = DB.DB.Collection("UserLog") + DB.CSystemLog = DB.DB.Collection("SystemLog") + DB.CInvestigation = DB.DB.Collection("Investigation") + DB.CTrajectory = DB.DB.Collection("Trajectory") + DB.CIcons = DB.DB.Collection("Icons") + DB.CTopMenus = DB.DB.Collection("TopMenus") + DB.CDevice = DB.DB.Collection("Device") + DelayMessage.CDelayMessage = DB.DB.Collection("DelayMessage") + DelayMessage.CDelayErrorLog = DB.DB.Collection("DelayErrorLog") // 连接redis DB.Redis = Cache.NewRedis(&Cache.RedisOpts{ conf.RedisPath, "", 0, - 20, + 200, 20, 0, }) - //设置模式 - DB.DBSession.SetMode(mgo.Monotonic, true) - //获取文档集 - DB.DB = DB.DBSession.DB(conf.DbName) - DB.DB.Login(conf.DbUser, conf.DbPassword) - - DB.CItem = DB.DB.C("Item") - DB.CComplaint = DB.DB.C("Complaint") - DB.CInvestigation = DB.DB.C("Investigation") - DB.CMember = DB.DB.C("Member") - DB.CCommodity = DB.DB.C("Commodity") - DB.CTags = DB.DB.C("Tags") - DB.CScenic = DB.DB.C("Scenic") - DB.CLine = DB.DB.C("Line") - DB.CUserLog = DB.DB.C("UserLog") - DB.CSystemLog = DB.DB.C("SystemLog") - DB.CInvestigation = DB.DB.C("Investigation") - DB.CTrajectory = DB.DB.C("Trajectory") - DB.CIcons = DB.DB.C("Icons") - DB.CTopMenus = DB.DB.C("TopMenus") - DB.CDevice = DB.DB.C("Device") - DelayMessage.CDelayMessage = DB.DB.C("DelayMessage") - DelayMessage.CDelayErrorLog = DB.DB.C("DelayErrorLog") - - - // 设置接口地址 - //controllers := LeYouTu.Controllers{} - //controllers.SetLayout(Api.Layout) - r := gin.Default() //r.Static("/.well-known", "./.well-known/") r.GET("/AllItems", Api.AllItems) @@ -103,6 +113,7 @@ func main() { r.POST("/UpdateItemTime", Api.UpdateItemTime) r.GET("/AllScenic", Api.AllScenic) r.POST("/UserLog", Api.UserLog) + r.GET("/AllUserLog", Api.AllUserLog) r.POST("/Sms/Send", Api.Send) r.POST("/Investigation/Save", Api.SaveInvestigation) r.GET("/Investigation/List", Api.AllInvestigation) @@ -118,13 +129,13 @@ func main() { r.POST("/TopMenus/Update", Api.UpdateTopMenus) r.GET("/TopMenus/All", Api.AllTopMenus) r.POST("/RegisterDevice", Api.RegisterDevice) + r.POST("/RemoveUser", Api.RemoveUser) //r.GET("/ws", Api.WsPage) r.Static("/Upload", "./Upload") r.Static("/Console", "./Console") r.Static("/Policy", dir+"/Policy") - r.GET("MP_verify_R9xuhLXYcVbdDDNk.txt", func(c *gin.Context) { c.String(200, "R9xuhLXYcVbdDDNk") }) @@ -139,18 +150,25 @@ func main() { }() // -初始化数据 - var aMessage []DelayMessage.Message - DelayMessage.CDelayMessage.Find(bson.M{}).All(&aMessage) - nowTimeU := time.Now().Unix() - for i := 0; i < len(aMessage); i++ { - iDelayTIme := aMessage[i].DelayTime - nowTimeU - - if iDelayTIme < 0 { - iDelayTIme = 1 + if cur, err := DelayMessage.CDelayMessage.Find(tools.GetContext(), bson.M{}); err == nil { + defer cur.Close(tools.GetContext()) + for cur.Next(tools.GetContext()) { + var message DelayMessage.Message + err := cur.Decode(&message) + tools.CheckError(err) + + nowTimeU := time.Now().Unix() + iDelayTIme := message.DelayTime - nowTimeU + + if iDelayTIme < 0 { + iDelayTIme = 1 + } + DelayMessage.GlobalDM.AddTask(time.Now().Add(time.Second*time.Duration(iDelayTIme)), DelayMessage.Callback, &message) + log.Println("增加提醒任务", message) } - DelayMessage.GlobalDM.AddTask(time.Now().Add(time.Second*time.Duration(iDelayTIme)), DelayMessage.Callback, &aMessage[i]) + } else { + spew.Dump(err) } - println("增加", len(aMessage), "条提醒任务") r.Run(":8080") } diff --git a/main2.go b/main2.go new file mode 100644 index 0000000..e204d34 --- /dev/null +++ b/main2.go @@ -0,0 +1,83 @@ +package main + +import ( + "context" + "fmt" + "github.com/gin-gonic/gin" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" + "log" + "time" +) + +var ( + client *mongo.Client + err error + result *mongo.InsertOneResult + collection *mongo.Collection +) + +// @APIVersion 1.0.0 +// @APITitle 乐游图后端接口文档 +// @BasePath 正式 leyoutu.st-i.com.cn; 测试 letu.api.imagchina.com +func main() { + + // Set client options + clientOptions := options.Client().ApplyURI("mongodb://localhost:27017") + clientOptions.SetLocalThreshold(3 * time.Second) //只使用与mongo操作耗时小于3秒的 + clientOptions.SetMaxConnIdleTime(5 * time.Second) //指定连接可以保持空闲的最大毫秒数 + clientOptions.SetMaxPoolSize(4096) //使用最大的连接数 + + // Connect to MongoDB + client, err = mongo.Connect(context.TODO(), clientOptions) + + if err != nil { + log.Fatal(err) + } + + // Check the connection + err = client.Ping(context.TODO(), nil) + + if err != nil { + log.Fatal(err) + } + + fmt.Println("Connected to MongoDB!") + + collection = client.Database("LeYouTu").Collection("LogRecord") + + r := gin.Default() + r.GET("/AllScenic", func(c *gin.Context) { + c.Header("Access-Control-Allow-Origin", c.Request.Header.Get("Origin")) + c.Header("Access-Control-Allow-Credentials", "true") + + //var aItems = DB.SItem{} + //if err = collection.FindOne(context.TODO(), bson.D{{}}).Decode(&aItems); err != nil { + // println(err) + //} + + record := &LogRecord{ + JobName: "job10", + Command: "echo hello", + Err: "", + Content: "hello", + } + + if result, err = collection.InsertOne(context.TODO(), record); err != nil { + fmt.Println(err) + return + } + + c.JSON(200, "ok") + + }) + + r.Run(":8080") +} + +type LogRecord struct { + JobName string `bson:"jobName"` // 任务名 + Command string `bson:"command"` // shell命令 + Err string `bson:"err"` // 脚本错误 + Content string `bson:"content"` // 脚本输出 +} -- libgit2 0.21.0