using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TRS.Export.BLL;
using TRS.Export.Common;
using TRS.Export.Entity;
using TRS.Export.FrameEntity.Constants;
using TRS.Export.FrameEntity.Enums;
using TRS.Export.FrameProvider;
using TRS.Export.Param.Bases;
using TRS.Export.Scheduler.Interfaces;
using TRS.Export.Business;
using TRS.Export.Service.API;
using Newtonsoft.Json;

namespace TRS.Export.Scheduler.Schedulers.Pushs
{
public class PushsTaobaoApiSourceScheduler : IScheduler
{
private readonly string PCS_API = ConfigurationManager.AppSettings["PCSReceiveAPI"];

private readonly string TWX_API = ConfigurationManager.AppSettings["TaoBaoOrderAPI"];

private readonly string PCS_RECEIVE_CODES = ConfigurationManager.AppSettings["PCSReceiveCodes"];

private readonly string TWX_REJECT_CODES = ConfigurationManager.AppSettings["TWXRejectCodes"];

private readonly string PCS_RECEIVE_OPEN = ConfigurationManager.AppSettings["PCSReceiveOpen"];

private readonly string TWX_RECEIVE_OPEN = ConfigurationManager.AppSettings["TWXReceiveOpen"];

private readonly TaoBaoAPISourceBLL m_objSourceBLL = new TaoBaoAPISourceBLL();

private readonly TaoBaoAPISource_SucessBLL m_objSourceSucessBLL = new TaoBaoAPISource_SucessBLL();

private readonly string PATH = @"D:\Beyond.TWX.JobApp.Log\PushsTaobaoApiSource";
string ExceptionTel = ConfigurationManager.AppSettings["ExceptionTelNumbers"];

public int SleepInterval { get; set; }

public string[] Args { get; set; }

public PushsTaobaoApiSourceScheduler()
{
SleepInterval = 2000;
}

public void Execute()
{

if (Args == null || Args.Length == 0)
{
Console.WriteLine("参数不能为空!");
return;
}

string threadName = string.Format("报文解析后台Job-{0}", "后缀");
string[] arrays = Args[0].Split('/');

while (true)
{
List<Task> tasks = new List<Task>();
foreach (var value in arrays)
{
tasks.Add(Task.Factory.StartNew(() =>
{
ExecuteTask(value);
}));
}

Task.WaitAll(tasks.ToArray());

Console.WriteLine("当前线程:[{0}],等待{1}秒后继续...{2}", threadName, SleepInterval / 1000, DateTime.Now);

Thread.Sleep(SleepInterval);
}
}

public void ExecuteTask(string suffix)
{
string threadName = string.Format("报文解析后台Job-{0}", suffix);

Console.WriteLine("当前线程:[{0}]{1}秒后继续...{2}", threadName, 0 / 1000, DateTime.Now);

var where = new WhereHelper<TaoBaoAPISource>(a => a.DoWith.In(0, 2, 3) && a.ActionTime < 4 && a.ID.Right(suffix.Split(',')));

List<TaoBaoAPISource> list = m_objSourceBLL.Select(where, 100);
foreach (var item in list)
{
ExecuteTask(item);
}
}

public void ExecuteTask(TaoBaoAPISource source)
{

try
{
Task<ResponseParam> task_pcs = Task.Factory.StartNew<ResponseParam>(() => { return ExecuteTaskPcs(source); });

Task<ResponseParam> task_twx = Task.Factory.StartNew<ResponseParam>(() => { return ExecuteTaskTwx(source); });

Task.WaitAll(task_pcs, task_twx);

if (!task_pcs.Result.success && task_pcs.Result.msg_code == "PCS" || !task_twx.Result.success && task_twx.Result.msg_code == "TWX")
{
if (task_pcs.Result.success)
{
source.DoWith = 2;
}

if (task_twx.Result.success)
{
source.DoWith = 3;
}

ExecuteDoWith(source);

Console.WriteLine("编号:{0}分发失败,开始重新尝试!", source.ID);
}
else
{
ExecuteBackup(source);

Console.WriteLine("编号:{0}分发成功,已经备份数据!", source.ID);
}
}
catch (Exception ex)
{
if (ex != null)
{
//日志记录异常
LogHelper.Info(ex.Message + "\n" + ex.Source + "\n" + ex.StackTrace, PATH);
//发送短信
SendMessageParam param = new SendMessageParam()
{
Destination = "中国",
Mobile = String.IsNullOrEmpty(ExceptionTel) ? "13728938720" : ExceptionTel,
Message = "分发job出现异常"
};
string req_content = JsonConvert.SerializeObject(param);
ResponseParam response = new SendMessageAPI().Send(req_content);
}

}
}

#region 分发报文调用PCS接口
public ResponseParam ExecuteTaskPcs(TaoBaoAPISource source)
{
Stopwatch watch = new Stopwatch();
watch.Start();

ResponseParam resonse = new ResponseParam();

if (source.DoWith == 2)
{
resonse.success = true;
resonse.msg_code = "PCS";
resonse.msg = string.Format("编号:{0}分发PCS系统成功,不能重复分发!", source.ID);

Console.WriteLine("{0}!耗时:{1} {2} {3}", resonse.msg, 0, "", DateTime.Now);

return resonse;
}

string urlDecode = source.ApiContent.UrlDecode();
string[] pcs_codes = PCS_RECEIVE_CODES.Split('|');
foreach (var code in pcs_codes)
{
if (urlDecode.IndexOf(code) > -1)
{
resonse.success = true;

break;
}
}

if (!resonse.success)
{
resonse.msg_code = "TWX";
resonse.msg = string.Format("编号:{0}不是PCS系统订单!", source.ID);
}
else
{
resonse.msg_code = "PCS";

string result = new HttpHelper().Execute(PCS_API, source.ApiContent);
if (!result.IsNullOrEmpty())
{
resonse.msg = string.Format("编号:{0}分发PCS系统成功", source.ID);
resonse.success = result.IndexOf("true") > -1;
}
else
{
resonse.msg = string.Format("编号:{0}分发PCS系统失败", source.ID);
resonse.success = false;
}
}

watch.Stop();

Console.WriteLine("{0}!耗时:{1} {2} {3}", resonse.msg, watch.ElapsedMilliseconds / 1000.00, "", DateTime.Now);

return resonse;
}
#endregion

#region 分发报文到TWX接口
public ResponseParam ExecuteTaskTwx(TaoBaoAPISource source)
{
Stopwatch watch = new Stopwatch();
watch.Start();

ResponseParam resonse = new ResponseParam();

if (source.DoWith == 3)
{
resonse.success = true;
resonse.msg_code = "TWX";
resonse.msg = string.Format("编号:{0}分发TWX系统成功,不能重复分发!", source.ID);

Console.WriteLine("{0}!耗时:{1} {2} {3}", resonse.msg, 0, "", DateTime.Now);

return resonse;
}

string urlDecode = source.ApiContent.UrlDecode();
string[] twx_codes = TWX_REJECT_CODES.Split('|');
foreach (var code in twx_codes)
{
if (urlDecode.IndexOf(code) > -1)
{
resonse.success = true;

break;
}
}

if (resonse.success)
{
resonse.success = false;
resonse.msg_code = "PCS";
resonse.msg = string.Format("编号:{0}不是TWX系统订单!", source.ID);
}
else
{
resonse.msg_code = "TWX";

string result = new HttpHelper().Execute(TWX_API, source.ApiContent);
if (!result.IsNullOrEmpty())
{
resonse.msg = string.Format("编号:{0}分发TWX系统成功", source.ID);
resonse.success = result.IndexOf("true") > -1;
}
else
{
resonse.msg = string.Format("编号:{0}分发TWX系统失败", source.ID);
resonse.success = false;
}
}

watch.Stop();

Console.WriteLine("{0}!耗时:{1} {2} {3}", resonse.msg, watch.ElapsedMilliseconds / 1000.00, "", DateTime.Now);

return resonse;
}
#endregion

public ResponseParam ExecuteBackup(TaoBaoAPISource source)
{
ResponseParam response = new ResponseParam();

string content = source.ApiContent.UrlDecode();
string tradeOrderId = StringHelper.GetValueByCutStr(ref content, "<tradeOrderId>", "</tradeOrderId>", false);
if (string.IsNullOrEmpty(tradeOrderId))
{
tradeOrderId = StringHelper.GetValueByCutStr(ref content, "<logisticsOrderCode>", "</logisticsOrderCode>", false);
}

string columns = "ID,ApiContent,CreateTime,FinishTime,TradeOrderID";
string values = "@ID,@ApiContent,@CreateTime,@FinishTime,@TradeOrderID";
string strTableName = string.Format("TaoBaoAPISource_Sucess_Log{0}", DateTime.Today.ToString("yyMM"));
string commandText = string.Format(SqlConstants.SQL_INSERT_FORMAT, strTableName, columns, values);
string connectionString = ConfigurationManager.AppSettings["SqlServer0"];

var param = new { ID = source.ID, ApiContent = source.ApiContent, CreateTime = source.CreateTime, FinishTime = DateTime.Now, TradeOrderID = (tradeOrderId ?? "").Trim() };

int effect = DapperSqlHelper.Execute(commandText, param, connectionString);

response.success = effect > 0;
if (response.success)
{
m_objSourceBLL.Delete(source);
}

return response;
}

public void ExecuteDoWith(TaoBaoAPISource source)
{
TaoBaoAPISource update = new TaoBaoAPISource();
update.ID = source.ID;
update.DoWith = source.DoWith;

if (source.DoWith != 0)
{
update.ActionTime = source.ActionTime + 1;
}

m_objSourceBLL.Update(update);
}
}
}

淘海外分发Job 多线程demo的更多相关文章

  1. Java中的多线程Demo

    一.关于Java多线程中的一些概念 1.1 线程基本概念 从JDK1.5开始,Java提供了3中方式来创建.启动多线程: 方式一(不推荐).通过继承Thread类来创建线程类,重写run()方法作为线 ...

  2. Python简单的多线程demo:装逼写法

    用面向对象来写多线程: import threading class MyThread(threading.Thread): def __init__(self, n): super(MyThread ...

  3. Python简单的多线程demo:常用写法

    简单多线程实现:启动50个线程,并计算执行时间. import threading import time def run(n): time.sleep(3) print("task:&qu ...

  4. 多线程demo,订单重复支付

    背景描述,一个商城网站,一个订单支付方案有多个1.金额支付2.积分支付3.工资支付(分期和全额),所以一个订单的方案可能有1:有1.2,或1.2.3 状态,1.订单状态,2,支付状态==>多方案 ...

  5. 有返回值的多线程demo

    package com.jimmy.demo.util; import java.util.HashMap;import java.util.concurrent.*;import java.util ...

  6. 多线程Demo

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  7. pThread多线程demo

    #import "ViewController.h" #import <pthread.h> @interface ViewController () @end @im ...

  8. Java的Socket通信----通过 Socket 实现 TCP 编程之多线程demo(2)

    JAVA Socket简介 所谓socket 通常也称作”套接字“,用于描述IP地址和端口,是一个通信链的句柄.应用程序通常通过”套接字”向网络发出请求或者应答网络请求. import java.io ...

  9. c++11 跨平台多线程demo和qt 静态链接(std::thread有join函数,设置 QMAKE_LFLAGS = -static)

    #include <stdio.h>#include <stdlib.h> #include <chrono> // std::chrono::seconds#in ...

随机推荐

  1. 搭建wordpress

    https://www.themepark.com.cn/xcjxgwordpressdzdyglyd.html

  2. post 传递参数中包含 html 代码解决办法,js加密,.net解密

    今天遇到一个问题,就是用post方式传递参数,程序在vs中完美调试,但是在iis中,就无法运行了,显示传递的参数获取不到,报错了,查看浏览器请求情况,错误500,服务器内部错误,当时第一想法是接收方式 ...

  3. 网络爬虫之scrapy框架详解

    twisted介绍 Twisted是用Python实现的基于事件驱动的网络引擎框架,scrapy正是依赖于twisted, 它是基于事件循环的异步非阻塞网络框架,可以实现爬虫的并发. twisted是 ...

  4. 为什么说”人生苦短,我用python“?

    本文不扯什么大道理,只是先介绍Python的背景,然后从实用的角度出发举一两个真实栗子. ​ 首先要想了解要一门语言的好坏,或者为什么招程序员喜欢(卧槽,原来程序员喜欢不是女朋友?)我们的先从语言的产 ...

  5. django 模板语言之 filter 自定义模板

    可以自己写python函数放在模板语言里用 这种方法是django里面的 filter {{ item.event_start|date:"Y-m-d H:i:s"}} {{ bi ...

  6. SVM数学原理推导&鸢尾花实例

    //看了多少遍SVM的数学原理讲解,就是不懂,对偶形式推导也是不懂,看来我真的是不太适合学数学啊,这是面试前最后一次认真的看,并且使用了sklearn包中的SVM来进行实现了一个鸢尾花分类的实例,进行 ...

  7. Redis持久化及复制

    一.持久化的两种方式 1.RDB: RDB是在指定时间间隔内生成数据集的时间点快照(point-in-time snapshot)持久化,它是记录一段时间内的操作,一段时间内操作超过多少次就持久化.默 ...

  8. Shiro安全框架入门篇

    一.Shiro框架介绍 Apache Shiro是Java的一个安全框架,旨在简化身份验证和授权.Shiro在JavaSE和JavaEE项目中都可以使用.它主要用来处理身份认证,授权,企业会话管理和加 ...

  9. Spark高级数据分析· 2数据分析

    wget https://archive.ics.uci.edu/ml/machine-learning-databases/00210/donation.zip 数据清洗 cd /Users/eri ...

  10. c++第三十一天

    p159~p164:switch语句1.例程:统计文本中五个元音字母出现的次数.(利用输入输出重定向测试) $ a <input.txt>output.txt #include <i ...