package jobcron import ( "SCRM/service" "SCRM/utils" "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" "strings" "time" "github.com/astaxie/beego" "github.com/robfig/cron" ) // cron表达式 https://www.cnblogs.com/zuxingyu/p/6023919.html var activityShortUrlCronJob *cron.Cron func init() { activityShortUrlCronJob = cron.New() spec := "0 0 0 * * ?" // 每天晚上12点整检查活动短链接库存充不充足 activityShortUrlCronJob.AddFunc(spec, func() { CreateActivityShortURLIfNeeded() }) } type CreateShortURLServiceMaxId struct { Value int } func CreateActivityShortURLIfNeeded() { var maxActivityId CreateShortURLServiceMaxId service.PatientReadDB().Raw("SELECT MAX(id) AS value FROM sgj_patient_activity").Scan(&maxActivityId) utils.TraceLog("当前最大的活动 ID 为:%v", maxActivityId) var maxShortURLId CreateShortURLServiceMaxId service.PatientReadDB().Raw("SELECT MAX(id) AS value FROM sgj_patient_activity_wx_share").Scan(&maxShortURLId) utils.TraceLog("当前最大的活动短链接 ID 为:%v", maxShortURLId) if maxShortURLId.Value-maxActivityId.Value <= 300 { utils.TraceLog("即将生成更多活动短链接") go CreateMoreActivityShortURL(maxShortURLId.Value) } else { utils.TraceLog("活动短链接充足,无需生成") } } // 新浪短链接服务示例 https://www.cnblogs.com/azure/archive/2012/08/29/WeiboAPI.html func CreateMoreActivityShortURL(lastShortURLID int) { var maxUrlCountPerRequest int = 20 createCount, _ := beego.AppConfig.Int("create_short_url_count_every_time") pageCount := createCount / maxUrlCountPerRequest tx := service.PatientWriteDB().Begin() for i := 0; i < pageCount; i++ { longURLParams := make([]string, 0, maxUrlCountPerRequest) for longURLIndex := 1; longURLIndex < maxUrlCountPerRequest+1; longURLIndex++ { id := lastShortURLID + i*maxUrlCountPerRequest + longURLIndex param := fmt.Sprintf("url_long=%v", fmt.Sprintf("%v/weixin/activity/%v", beego.AppConfig.String("weixinwebdomain"), id)) longURLParams = append(longURLParams, param) } urlStr := fmt.Sprintf("http://api.weibo.com/2/short_url/shorten.json?source=2849184197&%v", strings.Join(longURLParams, "&")) u, _ := url.Parse(urlStr) u.RawQuery = u.Query().Encode() // fmt.Println(u.String()) resp, requestErr := http.Get(u.String()) if requestErr != nil { utils.ErrorLog("http.Get error: %v", requestErr) continue } result, readErr := ioutil.ReadAll(resp.Body) resp.Body.Close() if readErr != nil { utils.ErrorLog("ioutil.ReadAll error: %v", readErr) continue } // fmt.Println(string(result)) var respJSON map[string]interface{} if err := json.Unmarshal([]byte(string(result)), &respJSON); err != nil { utils.ErrorLog("json.Unmarshal error: %v\n", err) continue } // fmt.Printf("resp: %v\n", respJSON) if respJSON["error"] != nil { utils.ErrorLog("request error: %v\n", respJSON) continue } urlJSONs := respJSON["urls"].([]interface{}) now := time.Now().Unix() valueStrs := make([]string, 0, len(urlJSONs)) values := make([]interface{}, 0, len(urlJSONs)*9) for index, url := range urlJSONs { urlJSON := url.(map[string]interface{}) shortURL := urlJSON["url_short"].(string) fmt.Println("shortURL是什么") id := lastShortURLID + i*maxUrlCountPerRequest + (index + 1) // CreateActivityWxShareWithShortURL(id, shortURL) // (`id`,`activity_id`,`title`,`subtitle`,`image`,`status`,`ctime`,`mtime`,`short_url`) valueStrs = append(valueStrs, "(?, ?, ?, ?, ?, ?, ?, ?, ?)") values = append(values, id) values = append(values, id) values = append(values, "") values = append(values, "") values = append(values, "") values = append(values, 1) values = append(values, now) values = append(values, now) values = append(values, shortURL) } sql := fmt.Sprintf("INSERT INTO sgj_patient_activity_wx_share (id, activity_id, title, subtitle, image, status, ctime, mtime, short_url) VALUES %v;", strings.Join(valueStrs, ", ")) if err := tx.Exec(sql, values...).Error; err != nil { utils.ErrorLog("插入活动短链接失败: %v", err) tx.Rollback() break } } tx.Commit() utils.TraceLog("完成生成更多活动短链接") } func BeginCreateActivityShortURLCronJob() { activityShortUrlCronJob.Start() }