Commit aad13101 by wang

主动推送京东

parent 0e2b6514
package JD
//获取京东token相关信息
const Appkey ="appKeyliexin"
const secretKey ="secretkeyliexin"
const UserName ="liexin-ceshi"
const Password ="liexin-ceshi"
//api地址
const GetTokenUrl = "http://bus-union.jd.com/component/getAccessToken" //获取token地址
const PushUrl = "bus-union.jd.com/component/http/JSON/standardProduct/input"//输出到JD
//log key
const jdserver_err = "jdserver_err"
//京东token信息 redis key set
const jd_client_token_redis_key = "jd_client_token"
\ No newline at end of file
package JD
//jdGetToken res
type JdRes struct {
ResponseData interface{} `json:"responseData"`
ResponseCode interface{} `json:"responseCode"`
Success bool `json:"success"`
ResponseMessage interface{} `json:"responseMessage"`
}
package main
import (
"fmt"
"golang_open_platform/JD"
)
func main() {
time:=int64(1616745725993)
expires:=int64(86400000)
fmt.Println((time+expires))
panic("kfdlf")
skudata:=GetSkuData()
JD.NewJdServer().PushData("sku",skudata)
}
//获取skudata并返回了json
func GetSkuData() string {
skudata:=`[
{
"brand_id": 30,
"goods_id": 10048,
"goods_images": "http://img.ichunt.com/test/images/goods/31/c8/31c8b5418f733d75b1aad5f12744a14f.jpg",
"goods_name": "T1",
"moq": 100,
"mpq": 100,
"stock": 0,
"supplier_name": "海南供应商"
},
{
"brand_id": 30,
"goods_id": 100487,
"goods_images": "http://img.ichunt.com/test/images/goods/31/c8/31c8b5418f733d75b1aad5f12744a14f.jpg",
"goods_name": "T1",
"moq": 100,
"mpq": 100,
"stock": 0,
"supplier_name": "海南供应商"
}
]`
return skudata
}
package JD
import (
"fmt"
"github.com/guonaihong/gout"
"strconv"
"time"
)
type JdServer struct {
Token
}
func NewJdServer() *JdServer{
return &JdServer{}
}
//推送数据到京东
func (this *JdServer) PushData(pushType string ,data interface{}) {
token:=this.getKoken()
return
header:=gout.H{"Authorization": token}
formData:=map[string]interface{}{
"user_id":"liexin_1",
"type":pushType,
"data":data,
"time":strconv.FormatInt(time.Now().UnixNano()/1e6, 10),
}
jdRes:=JdRes{}
err:=gout.POST(PushUrl).Debug(false).SetHeader(header).SetForm(formData).BindJSON(&jdRes).Do()
if(err!=nil){
msg:=fmt.Sprintf("请求京东服务报错,url:%s,err:%s,data:%v",PushUrl,err.Error(),formData)
RecordErrLog(msg)
panic(nil)
}
if(jdRes.Success==false){
msg:=fmt.Sprintf("code:%v,msg:%v",jdRes.ResponseCode,jdRes.ResponseMessage)
RecordErrLog(msg)
panic(nil)
}
}
package JD
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/gogf/gf/util/gconv"
"github.com/gomodule/redigo/redis"
"github.com/guonaihong/gout"
"github.com/syyongx/php2go"
"golang_open_platform/pkg/gredis"
"strconv"
"time"
)
type JdRequest struct {
GrantType interface{}`json:"grantType"`
AppKey interface{} `json:"appKey"`
UserName interface{} `json:"userName"`
Password interface{} `json:"password"`
RequestTime interface{} `json:"requestTime"`
Sign interface{} `json:"sign"`
Scope interface{} `json:"scope"`
}
type AccessTokenData struct {
AccessToken string `json:"accessToken"`
Time int64 `json:"time"`
ExpiresIn int64 `json:"expires_in"`
RefreshTokenExpires int64 `json:"RefreshTokenExpires`
}
type Token struct {
}
func (this *Token) getKoken() string {
//return "E9E647D9DEEF17B1770C02153D8A4DCA"
token:=this.getTokenCache()
if(token!=""){
return token
}
return this.getRealToken()
}
//获取真实token
func (this *Token)getRealToken() string {
requestTime:=strconv.FormatInt(time.Now().UnixNano()/1e6, 10)
jdRes:=JdRes{}
jdRequest:=JdRequest{}
jdRequest.GrantType="accessToken"
jdRequest.AppKey=Appkey
jdRequest.UserName=UserName
jdRequest.Password=php2go.Strtoupper(php2go.Md5(php2go.Base64Encode(Password+requestTime)))
jdRequest.RequestTime=requestTime
jdRequest.Sign=this.getSignString(jdRequest)
jdRequest.Scope=""
err:=gout.POST(GetTokenUrl).Debug(true).SetForm(jdRequest).BindJSON(&jdRes).Do()
if(err!=nil){
panic(err.Error())
}
if(jdRes.Success==false){
msg:=fmt.Sprintf("code:%v,msg:%v",jdRes.ResponseCode,jdRes.ResponseMessage)
panic(msg)
}
if tokenDataMap,ok:= jdRes.ResponseData.(map[string]interface{});ok{
this.setTokenCache(tokenDataMap)//存token
return gconv.String(tokenDataMap["accessToken"])//返回token
}else{
panic("responseData 不符合格式 ")
}
}
//设置缓存token
func (this *Token) setTokenCache(tokenMapData map[string]interface{}) {
redisWriteConn := gredis.Conn("search_w")
defer redisWriteConn.Close()
tokenMapData["realExpires"]=gconv.Int64(tokenMapData["expiresIn"])+gconv.Int64(tokenMapData["time"])*1000//毫秒
bytes,err:=json.Marshal(tokenMapData)
if(err!=nil){
RecordErrLog("设置缓存token,json.Marshal 报错,err:"+err.Error())
panic("")
}
_,err=redisWriteConn.Do("Set",jd_client_token_redis_key,string(bytes))
if(err!=nil){
RecordErrLog("设置缓存token,redis SET 报错,err:"+err.Error())
panic("")
}
}
/**
1.先从redis读出token的数据(map)
2.后通过过期时间验证是否过期(或者是否离过期还有一个小时),如果是,返回空
3.如果不是,返回token
*/
func (this *Token) getTokenCache() string {
redisReadConn := gredis.Conn("search_r")
defer redisReadConn.Close()
bytes,err:=redis.Bytes(redisReadConn.Do("GET",jd_client_token_redis_key))
if(err!=nil && err!=redis.ErrNil){
RecordErrLog("获取缓存token,redis GET 报错,err:"+err.Error())
panic("")
}
if(err==redis.ErrNil||bytes==nil){
return ""
}
tokenInfo:=make(map[string]interface{})
err=json.Unmarshal(bytes,&tokenInfo)
if(err!=nil){
RecordErrLog(jdserver_err,"获取缓存token,json数据有误,err:"+err.Error()+"json:"+string(bytes))
panic(nil)
}
timeNow:=time.Now().Unix()*1000
realExpires:=gconv.Int64(tokenInfo["realExpires"])
s:=int64(55*60*1000)
if(realExpires-timeNow<=s){//距离过期小于等于55分钟就重新获取
return this.getRealToken()
}else{
return gconv.String(tokenInfo["accessToken"])
}
}
/**
签名加密
按照以下顺序将字符串拼接起来
appKey + userName + password + requestTime + grantType+ secretKey
将上述拼接的字符串使用 HMACSHA256 加密,
*/
func (this *Token) getSignString(jdRequest JdRequest) string{
str:=gconv.String(jdRequest.AppKey)+gconv.String(jdRequest.UserName)+gconv.String(jdRequest.Password)
str=str+gconv.String(jdRequest.RequestTime)+gconv.String(jdRequest.GrantType)+gconv.String(secretKey)
hmac:=hmac.New(sha256.New,gconv.Bytes(secretKey))
hmac.Write([]byte(str))
return hex.EncodeToString(hmac.Sum([]byte("")))
}
package JD
import (
"golang_open_platform/pkg/common"
syncLog "golang_open_platform/pkg/logger/sync"
"golang_open_platform/pkg/message"
)
func RecordErrLog(msg string,dingdingTtile ...string) {
msgTtile:="[京东推送]自动推送sku数据\n"
if(len(dingdingTtile)>0){
msgTtile=dingdingTtile[0]
}
syncLog.SyncInsertLog(jdserver_err,msg,syncLog.LogLevelFatal)
msg=msgTtile+"\n"+msg
res,err:=message.DingDingPush(msg)
if(err!=nil){
syncLog.SyncInsertLog(jdserver_err,"发送钉钉错误:"+string(res.Errcode)+"msg:"+res.Errmsg,syncLog.LogLevelFatal)
common.PrintStdout().Printf("发送钉钉错误:"+string(res.Errcode)+"msg:"+res.Errmsg)
}
}
package main
import (
"flag"
_ "github.com/ichunt2019/ichunt-micro-registry/registry/etcd"
"golang_open_platform/boot"
service "golang_open_platform/service/push_Jd"
)
/**
"{"accessToken":"A2CBD9BC81C338AB6DA38B6E822490B0","expiresIn":86400,"realExpires":1616986559326,"refreshToken":"A2CBD9BC81C338AB6DA38B6E822490B0","refreshTokenExpires":1616986559326,"time":1616986472926}"
"{"accessToken":"A2CBD9BC81C338AB6DA38B6E822490B0","expiresIn":85112,"realExpires":1616987760674112,"refreshTokenExpires":1616987845701,"time":1616987760589}"
*/
func main() {
var path string
flag.StringVar(&path, "config", "conf", "配置文件")
flag.Parse()
if err := boot.Boot(path); err != nil {
panic(err)
}
service.NewSkuPushService().PushJd()
//str:=GetSkuData()
//JD.RecordErrLog("测试","钉钉测试京东推送")
}
func GetSkuData() string {
skudata:=`[
{
"brand_id": 30,
"goods_id": 10048,
"goods_images": "http://img.ichunt.com/test/images/goods/31/c8/31c8b5418f733d75b1aad5f12744a14f.jpg",
"goods_name": "T1",
"moq": 100,
"mpq": 100,
"stock": 0,
"supplier_name": "海南供应商"
},
{
"brand_id": 30,
"goods_id": 100487,
"goods_images": "http://img.ichunt.com/test/images/goods/31/c8/31c8b5418f733d75b1aad5f12744a14f.jpg",
"goods_name": "T1",
"moq": 100,
"mpq": 100,
"stock": 0,
"supplier_name": "海南供应商"
}
]`
return skudata
}
\ No newline at end of file
......@@ -7,4 +7,7 @@ mode = debug
;api_domain = http://192.168.1.237:60014
api_domain = http://localhost:60014
;钉钉配置信息
[DINGDING]
;SEARCH_API_MONITOR = 6d0fa85e01a02c39347d011ae973fd21b76c6c7ce582d3ea470c6b65a318848d
SEARCH_API_MONITOR = 92917a6e090a8a39832c4843a579d6c6f9dfecc46fa275f8753ddee2b4399045
\ No newline at end of file
......@@ -283,6 +283,8 @@ func Md5(str string) string {
return hex.EncodeToString(hash.Sum(nil))
}
//非精确匹配,字符串截取向下80%,5个字符以下不截,5-10个截一个,10-20个向下取80%,20个以上向下取70%
func SubKeyWordStr(str string) string {
strLen := len(str)
......
package logger
import (
"fmt"
"github.com/ichunt2019/log"
"golang_open_platform/pkg/config"
"strings"
......@@ -23,7 +22,7 @@ var (
var once sync.Once
func Loginit() {
once.Do(func() {
fmt.Print("日志初始化开始")
//fmt.Print("日志初始化开始")
configs:=config.GetSectionValues("log_config")
logD=make(map[string]logger.LogInterface)
for _,configOne:=range configs{
......
package logger
const (
LogLevelDebug = iota
LogLevelTrace
LogLevelInfo
LogLevelWarn
LogLevelError
LogLevelFatal
)
const (
LogSplitTypeHour = iota
LogSplitTypeSize
)
func getLevelText(level int) string {
switch level {
case LogLevelDebug:
return "DEBUG"
case LogLevelTrace:
return "TRACE"
case LogLevelInfo:
return "INFO"
case LogLevelWarn:
return "WARN"
case LogLevelError:
return "ERROR"
case LogLevelFatal:
return "FATAL"
}
return "UNKNOWN"
}
func getLogLevel(level string) int {
switch level {
case "debug":
return LogLevelDebug
case "trace":
return LogLevelTrace
case "info":
return LogLevelInfo
case "warn":
return LogLevelWarn
case "error":
return LogLevelError
case "fatal":
return LogLevelFatal
default:
return LogLevelInfo
}
return LogLevelDebug
}
package logger
import (
"encoding/json"
"fmt"
"os"
"strings"
"time"
)
/**
@param path 路径 比如sku_save 即文件夹是 sku 文件名类似 是save_2020-12-10.log
@param msg 错误文本
@Level 默认是 logger.LogLevelInfo
*/
func SyncInsertLog(path string,msg string,Levels ...int) {
logConfig := make(map[string]string)
logConfig["log_chan_size"]="1000"
slicePath:=strings.Split(path, "_")
if(slicePath[0]=="" || slicePath[1]==""){
panic("配置文件出错:文件/路径配置出错;提示:第一个参数格式应为A_B")
}
logConfig["log_path"] = "logs/"+slicePath[0]
logConfig["log_name"] = slicePath[1]
logPath:="logs/"+slicePath[0]
logName:=slicePath[1]
if logName=="" {
logName = time.Now().Format("2006-01-02")
}else{
logName = logName+"_"+time.Now().Format("2006-01-02")
}
filename := fmt.Sprintf("%s/%s.log", logPath, logName)
createFile(logPath)
file, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0755)
defer file.Close()
if err != nil {
panic(fmt.Sprintf("open faile %s failed, err:%v", filename, err))
}
level:=LogLevelInfo
if(len(Levels)>0){
level=Levels[0]
}
//"fileName":"service_mapping.go","method":"service.test","lineNo":85
logData:=writeLog(level,msg)
fmt.Printf("%s;fileinfo:%s\n",msg,logData.Filename)
str,err :=json.Marshal(logData)
if err == nil{
fmt.Fprintf(file, string(str)+"\n")
}
}
//调用os.MkdirAll递归创建文件夹
func createFile(filePath string) error {
if !isExist(filePath) {
err := os.MkdirAll(filePath,os.ModePerm)
return err
}
return nil
}
// 判断所给路径文件/文件夹是否存在(返回true是存在)
func isExist(path string) bool {
_, err := os.Stat(path) //os.Stat获取文件信息
if err != nil {
if os.IsExist(err) {
return true
}
return false
}
return true
}
package logger
import (
"fmt"
"path"
"runtime"
"time"
)
type LogData struct {
Message string `json:"msg"`
TimeStr string `json:"dateStr"`
LevelStr string `json:"levelStr"`
Filename string `json:"fileName"`
FuncName string `json:"method"`
LineNo int `json:"lineNo"`
WarnAndFatal bool `json:"warnAndFatal"`
Req string `json:"request"`
}
//util.go 10
func GetLineInfo() (fileName string, funcName string, lineNo int) {
pc, file, line, ok := runtime.Caller(4)
if ok {
fileName = file
funcName = runtime.FuncForPC(pc).Name()
lineNo = line
}
return
}
/*
1. 当业务调用打日志的方法时,我们把日志相关的数据写入到chan(队列)
2. 然后我们有一个后台的线程不断的从chan里面获取这些日志,最终写入到文件。
*/
func writeLog(level int, format string, args ...interface{}) *LogData {
now := time.Now()
nowStr := now.Format("2006-01-02 15:04:05.999")
levelStr := getLevelText(level)
fileName, funcName, lineNo := GetLineInfo()
fileName = path.Base(fileName)
funcName = path.Base(funcName)
msg := fmt.Sprintf(format, args...)
logData := &LogData{
Message: msg,
TimeStr: nowStr,
LevelStr: levelStr,
Filename: fileName,
FuncName: funcName,
LineNo: lineNo,
WarnAndFatal: false,
}
if level == LogLevelError || level == LogLevelWarn || level == LogLevelFatal {
logData.WarnAndFatal = true
}
return logData
//fmt.Fprintf(file, "%s %s (%s:%s:%d) %s\n", nowStr, levelStr, fileName, funcName, lineNo, msg)
}
### 说明
#### 与京东交互第一个版本(目前已废弃)
我们提供api,让京东的人调用我们的数据,service 根目录下的 service_class 与 service_sku 是提供给京东的调用的api用到的service
#### 与京东数据交互的第二个版本
京东提供接口,我们把数据发送给京东。将第一版本的 service_class 与 service_sku复制一份放到 push_jd文件下,不想公用
package service
import (
"encoding/json"
"fmt"
"github.com/guonaihong/gout"
"github.com/tidwall/gjson"
"golang_open_platform/dao"
"golang_open_platform/model"
"golang_open_platform/open"
"golang_open_platform/pkg/common"
"golang_open_platform/pkg/config"
"golang_open_platform/pkg/e"
"strings"
)
type SkuService struct {
}
func NewSkuService() *SkuService{
return &SkuService{}
}
/*
用classId获取sku列表
*/
func (this *SkuService)GetSkuListByClass(req *model.QuerySkuCreq) (rsp *model.QuerySkuCrsp,err error ){
pageData,err:=dao.GetMongoOpenSku(req.ClassId,0)
if(err!=nil){
return nil,e.NewApiError("service error",open.OTHERERROR)
}
rsp=&model.QuerySkuCrsp{Count:pageData.Count,PageSize:10,Page:req.Page}
if(pageData.Count<=0){//没数据
return
}
if(req.Page>0){
//验证下page是否有效
/*if(math.Ceil(float64(pageData.Count/rsp.PageSize))<float64(req.Page)){
return nil,e.NewApiError("page invalid",open.PARAM1)
}*/
mongoOpenSku,err:=dao.GetMongoOpenSku(req.ClassId,req.Page)
if(err!=nil){
return nil,e.NewApiError("service error",open.OTHERERROR)
}
if(mongoOpenSku.SkuIds==""){
if(rsp.Count>0){
common.PrintStdout().Printf("classID:%d page %d ids 为空",req.ClassId,req.Page)
}
return rsp,nil
}
skuIds:=strings.Replace(mongoOpenSku.SkuIds," ",",",-1)
//skuIds
remoteData,err:=this.getRemoteSku(skuIds)
if(err!=nil){
common.PrintStdout().Printf(err.Error())
return rsp,e.NewApiError("service error",open.REMOTESKUINFO)
}
//field:=[]string{"goods_id","stock","ladder_price"}
field:=[]string{"goods_id","stock","ladder_price","update_time",}
//field:=[]string{"spu_id","attrs","supplier_name","goods_images","hk_delivery_time"}
rsp.SkuData=model.SkuFilter(*remoteData,field)
}
return rsp,nil
}
//获取sku列表完整字段
func (this *SkuService) GetSkuListFull(req * model.QuerySkuReq)(rsp *model.QuerySkuRsp,err error) {
//skuIds:=strings.Replace(req.GoodsIds," ",",",-1)
//skuIds
rsp=&model.QuerySkuRsp{}
remoteData,err:=this.getRemoteSku(req.GoodsIds)
if(err!=nil){
common.PrintStdout().Printf(err.Error())
return rsp,e.NewApiError("service error",open.REMOTESKUINFO)
}
field:=[]string{"goods_id","spu_id","brand_id","brand_name","goods_name", "stock","moq","mpq",
"class_id1","class_id2","class_id1_name","class_id2_name","attrs","ladder_price","supplier_name","goods_images",}
rsp.SkuData=model.SkuFilter(*remoteData,field)
return
}
//获取sku列表 价格库存相关字段
func (this *SkuService) GetSkuListPrice(req * model.QuerySkuReq)(rsp model.QuerySkuRsp,err error) {
remoteData,err:=this.getRemoteSku(req.GoodsIds)
if(err!=nil){
common.PrintStdout().Printf(err.Error())
return rsp,e.NewApiError("service error",open.REMOTESKUINFO)
}
field:=[]string{"goods_id","stock","ladder_price"}
rsp.SkuData=model.SkuFilter(*remoteData,field)
return
}
//获取sku列表 价格库存相关字段
func (this *SkuService) GetSkuListImages(req * model.QuerySkuReq)(rsp model.QuerySkuRsp,err error) {
remoteData,err:=this.getRemoteSku(req.GoodsIds)
if(err!=nil){
common.PrintStdout().Printf(err.Error())
return rsp,e.NewApiError("service error",open.REMOTESKUINFO)
}
field:=[]string{"goods_images","goods_id"}
rsp.SkuData=model.SkuFilter(*remoteData,field)
return
}
//获取远端商详接口
func (this *SkuService) getRemoteSku(ids string) (remoteData *model.RemoteSkuData,err error){
resStr:=""
err=gout.POST(config.Get("sku_server.api_domain").String()+"/synchronization")/*.Debug(true)*/.SetForm(gout.H{"goods_id": ids}).BindBody(&resStr).Do()
if(err!=nil){
return remoteData,fmt.Errorf("调用远端商详接口报错:"+err.Error())
}
gjsonRes:=gjson.Parse(resStr)
if(gjsonRes.Exists()==false){
return remoteData,fmt.Errorf("返回的参数不能被json解析")
}
if(gjsonRes.Get("errcode").Int()!=0){
msg:=gjsonRes.Get("errmsg").String()
return remoteData,fmt.Errorf(msg)
}
dataGjsonObj:=gjsonRes.Get("data")
if(dataGjsonObj.IsObject()==false){
return remoteData,fmt.Errorf("商详返回的 data数据格式不对")
}
remoteData=&model.RemoteSkuData{}
err=json.Unmarshal([]byte(dataGjsonObj.String()),remoteData)
if(err!=nil){
return remoteData,fmt.Errorf("data 不能被json.Unmarshal解析")
}
return remoteData,nil
}
package service
import (
"encoding/json"
"fmt"
"github.com/gogf/gf/util/gconv"
"golang_open_platform/JD"
"golang_open_platform/dao"
"golang_open_platform/model"
"golang_open_platform/pkg/common"
"golang_open_platform/pkg/e"
"golang_open_platform/pkg/message"
"time"
)
var classTotalCount int64//class2总数量
var skuTotalCont int64//sku总数量
var actTime int64 //当天开始时间
var endTime int64 //当天结束时间
var duration string //处理时长
type SkuPushService struct {
}
func NewSkuPushService() *SkuPushService{
return &SkuPushService{}
}
var skuService=NewSkuService()
func (this *SkuPushService)PushJd() {
actTime,endTime=GetDateTime()//固定住当天的开始时间和结束时间
start:=time.Now()
classId:=0
classRsp:=this.getClassList(classId)
//[遍历分类]
for _,classInfo:=range classRsp{//遍历一级分类
if(classInfo.ClassId!=0){
//this.pushForClass(classInfo.ClassId)//push其中一个一级分类id所包含的sku
class2Rsp:=this.getClassList(classInfo.ClassId)//获取二级分类
for _,classInfo:=range class2Rsp{//遍历二级分类
if(classInfo.ClassId!=0){
this.pushForClass(classInfo.ClassId)//push其中一个二级分类id所包含的sku
}
}
}
}
end:=time.Now()
duration=end.Sub(start).String()
this.dingdingSucessPush()
}
//push ClassID 包含的sku给京东
func (this *SkuPushService) pushForClass(classId int) {
if(classId!=0){
skuNum:=int64(0)
page:=1
for {
qskuReq:=&model.QuerySkuCreq{ClassId:classId,Page:page}
skuRsp,err:=skuService.GetSkuListByClass(qskuReq)
this.CheckError(err,"[GetSkuListByClass 错误];classID:"+string(classId))
if(len(skuRsp.SkuData)<=0){
common.PrintStdout().Printf("classID:%d,page:%d,sku为空",classId,page)
break
}
//[过滤不是当天更新的sku] updte_time处于当天的时间
newSkuInfo:=make([]map[string]interface{},0)
for _,skuInfoMap:=range skuRsp.SkuData{
if updateTime,ok:=skuInfoMap["update_time"];ok{
updateTime64:=gconv.Int64(updateTime)
if (updateTime64>actTime && updateTime64<=endTime){
newSkuInfo=append(newSkuInfo,skuInfoMap)
}
}
}
if(len(newSkuInfo)<=0){
break
}
//end
bytes,err:=json.Marshal(newSkuInfo)
this.CheckError(err,"[json.Marshal skudata 出错]")
JD.NewJdServer().PushData("sku",string(bytes))
skuNum+=int64(len(newSkuInfo))
classTotalCount++
page++
}
skuTotalCont+=skuNum
common.PrintStdout().Printf("classID:%d,推送 sku:%d 条",classId,skuNum)
}
}
//获取分类列表
func (this *SkuPushService) getClassList(parent_id int) (QueryClassRspS []model.QueryClassRsp) {
rsp,err:=dao.GetClassList(parent_id)
if(err!=nil){
JD.RecordErrLog(err.Error())
panic(nil)
}
if(len(rsp)<=0){
if(parent_id==0){
JD.RecordErrLog("parentID 为0的class没有数据")
panic(nil)
}
}
return rsp
}
//检测错误并加日志发送钉钉
func (this *SkuPushService) CheckError(err error,pre ...string) {
if err != nil {
preStr:=""
if(len(pre)>0){
preStr=pre[0]
}
if apiError,ok:=err.(*e.ApiError);ok{
msg:=fmt.Sprintf("%s,err:%s,code:%d",preStr,apiError.Error(),apiError.Code)
JD.RecordErrLog(msg)
panic(nil)
}else{
msg:=fmt.Sprintf("%s,err:%s",preStr,apiError.Error())
JD.RecordErrLog(msg)
panic(nil)
}
}
}
//钉钉发送成功
func (this *SkuPushService) dingdingSucessPush() {
msgTtile:="[京东推送]自动推送sku数据\n"
msgS:=fmt.Sprintf("总共推送class:%d个,sku:%d 条成功\n",classTotalCount,skuTotalCont)
msgt:=fmt.Sprintf("处理时长%s",duration)
msg:=msgTtile+msgS+msgt
res,err:=message.DingDingPush(msg)
if(err!=nil){
JD.RecordErrLog("发送钉钉错误:"+string(res.Errcode)+"msg:"+res.Errmsg)
panic(nil)
}
}
//获取当天0点和23点59分的时间戳
func GetDateTime() (int64,int64){
//date := time.Now().Format("2006-01-02")
date:="2020-11-16"
//获取当前时区
loc, _ := time.LoadLocation("Asia/Shanghai")
//日期当天0点时间戳(拼接字符串)
startDate := date+"_00:00:00"
startTime, _:= time.ParseInLocation("2006-01-02_15:04:05",startDate,loc)
//日期当天23时59分时间戳
endDate:=date+"_23:59:59"
end,_:=time.ParseInLocation("2006-01-02_15:04:05",endDate,loc)
//返回当天0点和23点59分的时间戳
return startTime.Unix(),end.Unix()
}
\ No newline at end of file
......@@ -100,7 +100,6 @@ func (this *SkuService) GetSkuListImages(req * model.QuerySkuReq)(rsp model.Quer
return
}
//获取远端商详接口
func (this *SkuService) getRemoteSku(ids string) (remoteData *model.RemoteSkuData,err error){
resStr:=""
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment