コード例 #1
0
ファイル: DefaultJdClient.cs プロジェクト: xiangwan/JdSdk2
 private T Execute <T>(IJdRequest <T> request, string accessToken, DateTime timestamp) where T : JdResponse
 {
     if (disableTrace)
     {
         return(DoExecute <T>(request, accessToken, timestamp));
     }
     else
     {
         try
         {
             return(DoExecute <T>(request, accessToken, timestamp));
         }
         catch (Exception e)
         {
             topLogger.Error(this.serverUrl + "\r\n" + e.StackTrace);
             throw e;
         }
     }
 }
コード例 #2
0
        private T DoExecute <T> (IJdRequest <T> request, string access_token, DateTime timestamp) where T : JdResponse
        {
            // 提前检查业务参数
            try {
                request.Validate();
            } catch (JdException e) {
                return(createErrorResponse <T> (e.ErrorCode, e.ErrorMsg));
            }

            // 添加协议级请求参数
            JdDictionary txtParams = new JdDictionary();

            txtParams.Add(METHOD, request.GetApiName());
            txtParams.Add(VERSION, "2.0");
            txtParams.Add(APP_KEY, appKey);
            txtParams.Add(TIMESTAMP, timestamp);
            if (access_token != null)
            {
                txtParams.Add(ACCESS_TOKEN, access_token);
            }
            txtParams.Add(PARAM_JSON, JsonConvert.ExportToString(request.GetParameters()));
            // 添加签名参数
            txtParams.Add(SIGN, JdUtils.SignJdRequest(txtParams, appSecret, true));
            string reqUrl = webUtils.BuildGetUrl(this.serverUrl, txtParams);

            try {
                string body;
                if (request is IJdUploadRequest <T> )                 // 是否需要上传文件
                {
                    IJdUploadRequest <T>           uRequest   = (IJdUploadRequest <T>)request;
                    IDictionary <string, FileItem> fileParams = JdUtils.CleanupDictionary(uRequest.GetFileParameters());
                    body = webUtils.DoPost(this.serverUrl, txtParams, fileParams);
                }
                else
                {
                    body = webUtils.DoPost(this.serverUrl, txtParams);
                }

                // 解释响应结果
                T rsp;
                if (disableParser)
                {
                    rsp      = Activator.CreateInstance <T> ();
                    rsp.Body = body;
                }
                else
                {
                    if (FORMAT_XML.Equals(format))
                    {
                        IJdParser tp = new JdXmlParser();
                        rsp = tp.Parse <T> (body);
                    }
                    else
                    {
                        IJdParser tp = new JdJsonParser();
                        rsp = tp.Parse <T> (body);
                    }
                }

                // 追踪错误的请求
                if (!disableTrace && rsp.IsError)
                {
                    StringBuilder sb = new StringBuilder(reqUrl).Append(" response error!\r\n").Append(rsp.Body);
                    JdLogger.Warn(sb.ToString());
                }
                return(rsp);
            } catch (Exception e) {
                if (!disableTrace)
                {
                    StringBuilder sb = new StringBuilder(reqUrl).Append(" request error!\r\n").Append(e.StackTrace);
                    JdLogger.Error(sb.ToString());
                }
                throw e;
            }
        }
コード例 #3
0
ファイル: HttpClient.cs プロジェクト: KqSMea8/HS.Admin
        public HttpResponse Post()
        {
            int          retriedCount;
            int          retry = conf.GetHttpConnectRetryCount() + 1;
            HttpResponse resp  = null;

            for (retriedCount = 1; retriedCount <= retry; retriedCount++)
            {
                try
                {
                    HttpWebRequest   con       = null;
                    System.IO.Stream outStream = null;
                    try
                    {
                        con           = GetConnection(conf.GetConnectUrl(), conf.GetHttpConnectionTimeout(), conf.GetHttpReadTimeout());
                        con.KeepAlive = true;

                        SetHeaders(con, conf.GetRequestHeader());
                        con.Method      = "POST";
                        con.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

                        string postParam = WebUtils.BuildQuery(parameters);
                        byte[] bytes     = System.Text.Encoding.UTF8.GetBytes(postParam);

                        outStream = con.GetRequestStream();
                        outStream.Write(bytes, 0, bytes.Length);
                        outStream.Close();

                        HttpWebResponse response     = (HttpWebResponse)con.GetResponse();
                        HttpStatusCode  responseCode = response.StatusCode;

                        if (HttpStatusCode.OK == responseCode)
                        {
                            log.Info("connect successful");

                            StringBuilder       respHeader      = new StringBuilder();
                            WebHeaderCollection responseHeaders = con.Headers;

                            foreach (string key in responseHeaders.AllKeys)
                            {
                                string[] values = responseHeaders.GetValues(key);

                                foreach (string value in values)
                                {
                                    if (key != null)
                                    {
                                        respHeader.Append(key).Append("=").Append(value);
                                    }
                                    else
                                    {
                                        respHeader.Append(value);
                                    }
                                    respHeader.Append(";");
                                }

                                log.Info("Response: " + respHeader.ToString());
                            }
                            resp = new HttpResponse(con);
                            return(resp);
                        }
                        else if (HttpStatusCode.BadRequest == responseCode)
                        {   //参数校验出错
                            log.Info("Request param is invalid,errmsg is:" + con.Headers.Get(StreamConstants.ERR_MSG_HEADER));
                            throw new JdCometSysErrorException("Server response err msg:" + con.Headers.Get(StreamConstants.ERR_MSG_HEADER));
                        }
                        else if (HttpStatusCode.Forbidden == responseCode)
                        {//服务端在发布,需要休眠一段时间
                            log.Info("Server is deploying,sleep " + retriedCount * conf.GetHttpConnectRetryInterval() + " seconds");
                            if (retriedCount == conf.GetHttpConnectRetryCount())
                            {
                                log.Info("May be server occure some error,please contact Jd tech support");
                                throw new JdCometSysErrorException("May be server occure some error,please contact Jd tech support");
                            }
                            try
                            {
                                Thread.Sleep(retriedCount * conf.GetHttpConnectRetryInterval() * 1000);
                            }
                            catch (Exception e)
                            {
                                //ignore;
                            }
                            continue;
                        }
                    }
                    catch (Exception e)
                    {
                        log.Error(e.Message);
                    }
                    finally
                    {
                        try
                        {
                            if (outStream != null)
                            {
                                outStream.Close();
                            }
                        }
                        catch (Exception ignore)
                        {
                        }
                    }
                }
                catch (Exception ioe)
                {
                    // connection timeout or read timeout
                    if (retriedCount == conf.GetHttpConnectRetryCount())
                    {
                        throw new JdCometSysErrorException(ioe.Message);
                    }
                }
                try
                {
                    log.Info("Sleeping " + conf.GetHttpConnectRetryInterval() + " seconds until the next retry.");
                    Thread.Sleep(retriedCount * conf.GetHttpConnectRetryInterval() * 1000);
                }
                catch (Exception ignore)
                {
                    //nothing to do
                }
            }
            return(resp);
        }
コード例 #4
0
ファイル: JdCometStreamImpl.cs プロジェクト: KqSMea8/HS.Admin
        void ControlThread(StreamMsgConsumeFactory msgConsumeFactory, ref bool bsJd, Configuration conf, JdCometStreamRequest cometReq)
        {
            long lastSleepTime = 0;

            while (!bsJd)
            {
                if (allSJd)
                {
                    break;
                }

                try
                {
                    if (StreamConstants.SERVER_DEPLOY.Equals(serverRespCode))
                    {   // 服务端在发布
                        logger.Info("Server is upgrade sleep " + conf.GetSleepTimeOfServerInUpgrade() + " seconds");
                        Thread.Sleep(conf.GetSleepTimeOfServerInUpgrade() * 1000);
                        StartConsumeThread(cometReq);
                    }
                    else if (/*客户端第一次发起连接请求*/
                        StreamConstants.CLIENT_FIRST_CONNECT.Equals(serverRespCode) ||
                        /*服务端主动断开了所有的连接*/
                        StreamConstants.SERVER_REHASH.Equals(serverRespCode) ||
                        /*连接到达最大时间*/
                        StreamConstants.CONNECT_REACH_MAX_TIME.Equals(serverRespCode) ||
                        /*在一些异常情况下需要重连*/
                        StreamConstants.RECONNECT.Equals(serverRespCode))
                    {
                        StartConsumeThread(cometReq);
                    }
                    else if (/*客户端自己把自己踢开*/
                        StreamConstants.CLIENT_KICKOFF.Equals(serverRespCode) ||
                        /*服务端把客户端踢开*/
                        StreamConstants.SERVER_KICKOFF.Equals(serverRespCode))
                    {
                        if ((StreamConstants.CLIENT_KICKOFF.Equals(serverRespCode) && !isReconnect) ||
                            StreamConstants.SERVER_KICKOFF.Equals(serverRespCode))
                        {
                            break;// 终止掉当前线程
                        }
                    }
                    else
                    {   //错误码设置出错,停止线程
                        bsJd = true;
                        break;
                    }
                    //连接成功,开始休眠
                    try
                    {
                        Monitor.Enter(objLock);
                        {
                            lastSleepTime = DateTime.Now.Ticks;

                            Monitor.Wait(objLock, conf.GetHttpReconnectInterval() * 1000);
                            if (DateTime.Now.Ticks - lastSleepTime >= (conf.GetHttpReconnectInterval()) * 1000 * 10000)
                            {
                                /*
                                 * 快要到达连接的最大时间了,需要重新发起连接
                                 */
                                serverRespCode = StreamConstants.RECONNECT;
                                isReconnect    = true;
                            }//否则,是由于某种原因被唤醒的
                        }
                    }
                    catch (Exception e)
                    {
                        logger.Error(e.Message);
                    }
                    finally
                    {
                        Monitor.Exit(objLock);
                    }
                }
                catch (Exception e)
                {
                    logger.Error("Occur some error,sJd the stream consume" + e.Message);
                    bsJd = true;
                    try
                    {
                        Monitor.Enter(objLock);
                        Monitor.PulseAll(objLock);
                    }
                    finally
                    {
                        Monitor.Exit(objLock);
                    }
                }
            }
            if (currentStreamImpl != null)
            {
                try
                {
                    currentStreamImpl.Close();
                }
                catch (Exception e)
                {
                    // ignore
                }
            }
            logger.Info("SJd stream consume");
        }
コード例 #5
0
ファイル: MessageStreamImpl.cs プロジェクト: KqSMea8/HS.Admin
        public override string ParseLine(string msg)
        {
            if (!string.IsNullOrEmpty(msg))
            {
                try
                {
                    Regex           rg      = new Regex(pattern, RegexOptions.Compiled);
                    MatchCollection matches = rg.Matches(msg);

                    if (matches.Count > 0)
                    {
                        string code = matches[0].Groups["code"].Value;

                        if (StreamConstants.NEW_MESSAGE.Equals(code))
                        {
                            return(matches[0].Groups["msg"].Value);
                        }
                        else if (StreamConstants.HEAT_BEAT.Equals(code))
                        {
                            msgListener.OnHeartBeat();
                        }
                        else if (StreamConstants.CONNECT_REACH_MAX_TIME.Equals(code))
                        {
                            msgListener.OnConnectReachMaxTime();
                            WakeUp(code);
                        }
                        else if (StreamConstants.DISCARD_MESSAGE.Equals(code))
                        {
                            msgListener.OnDiscardMsg(matches[0].Groups["msg"].Value.ToString());
                        }
                        else if (StreamConstants.SERVER_DEPLOY.Equals(code))
                        {
                            msgListener.OnServerUpgrade(matches[0].Groups["msg"].Value.ToString());
                            WakeUp(code);
                        }
                        else if (StreamConstants.SERVER_REHASH.Equals(code))
                        {
                            msgListener.OnServerRehash();
                            WakeUp(code);
                        }
                        else if (StreamConstants.CLIENT_KICKOFF.Equals(code))
                        {
                            msgListener.OnClientKickOff();
                            WakeUp(code);
                        }
                        else if (StreamConstants.SERVER_KICKOFF.Equals(code))
                        {
                            msgListener.OnServerKickOff();
                            WakeUp(code);
                        }
                        else if (StreamConstants.CONNECT_SUCCESS.Equals(code))
                        {
                            msgListener.OnConnectMsg(matches[0].Groups["msg"].Value);
                        }
                        else
                        {
                            msgListener.OnOtherMsg(matches[0].Groups["msg"].Value);
                        }
                    }
                }
                catch (Exception e)
                {
                    logger.Error("Message is invalid:" + msg + e.Message);
                    msgListener.OnException(e);
                    return(null);
                }
            }
            return(null);
        }