private void AddMessageHeader(IContextChannel channel, string cmd, bool iscompressjson, bool isencryptionjson, SerializeType serializetype, SysLoginRight loginright, Action callback) { using (var scope = new OperationContextScope(channel as IContextChannel)) { if (string.IsNullOrEmpty(cmd)) { cmd = ""; } HeaderParameter para = new HeaderParameter(); para.cmd = cmd; para.routerid = clientObj.RouterID; para.pluginname = clientObj.PluginName; //ReplyIdentify如果客户端创建连接为空,如果中间件连接上级中间件那就是本地中间件标识 para.replyidentify = null; para.beginidentify = BeginIdentify; para.endidentify = EndIdentify; para.token = loginright != null ? loginright.token : null; //clientObj.Token; para.iscompressjson = iscompressjson; para.isencryptionjson = isencryptionjson; para.serializetype = serializetype; para.LoginRight = loginright; para.NodePath = null; HeaderOperater.AddMessageHeader(OperationContext.Current.OutgoingMessageHeaders, para); callback(); } }
public IList <User> FindAll() { HeaderContext headercontext = HeaderOperater.GetServiceWcfHeader(OperationContext.Current); ITransaction t = Cat.GetProducer().NewTransaction("Data", "call wcf"); IMessageTree tree = Cat.GetManager().ThreadLocalMessageTree; tree.RootMessageId = headercontext.RootID; tree.ParentMessageId = headercontext.CorrelationState; tree.MessageId = headercontext.ParentID; List <User> list = new List <User>(); for (int i = 0; i < 30; i++) { User obj = new User(); obj.UserID = i + 1; obj.UserName = "******" + (i + 1); list.Add(obj); } Cat.GetProducer().LogEvent("Data In.Server", "FindAll", "0", "Success"); t.Status = "B"; t.Complete(); return(list); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string filename = Server.MapPath("~/config/catclient.xml"); Cat.Initialize(filename); ITransaction t = Cat.GetProducer().NewTransaction("URL", "demo.aspx"); IMessageTree tree = Cat.GetManager().ThreadLocalMessageTree; //创建传递的上下文信息 HeaderContext context = new HeaderContext(); context.AppName = ""; context.CorrelationState = tree.MessageId; context.RootID = tree.RootMessageId == null ? tree.MessageId : tree.RootMessageId; context.ParentID = Cat.GetManager().CreateMessageId(); context.Ip = ""; HeaderOperater.SetClientWcfHeader(context); Cat.GetProducer().LogEvent("URL", "Call", "0", "Call Start..."); Cat.GetProducer().LogEvent("RemoteCall", "PigeonRequest", "0", context.ParentID); IUserBll bll = WcfClient.GetProxy <IUserBll>(); IList <User> list = bll.FindAll(); Cat.GetProducer().LogEvent("URL", "Call", "0", "Call End..."); //注:上下文信息必须在创建后清除 HeaderOperater.ClearClientWcfHeader(); t.Status = "A"; t.Complete(); this.GridView1.DataSource = list; this.GridView1.DataBind(); } }
//路径执行到下一个节点 private static string PathNextRequest(string plugin, string controller, string method, string jsondata, HeaderParameter para) { string retJson = null; try { para.NodePath.NextStep(); //节点路径下一步 if (para.NodePath.IsEndMNode) //到达终节点 { //执行本地数据请求 retJson = LocalDataRequest(plugin, controller, method, jsondata, para); } else if (para.NodePath.nextMNodeDirection == "<up>")//向上 { ClientLink clientlink = SuperClient.CreateDataClient(); using (var scope = new OperationContextScope(clientlink.ClientObj.WcfService.InnerDuplexChannel as IContextChannel)) { HeaderOperater.AddMessageHeader(OperationContext.Current.OutgoingMessageHeaders, para); retJson = clientlink.ClientObj.WcfService.ProcessRequest(clientlink.ClientObj.ClientID, plugin, controller, method, jsondata); } } else if (para.NodePath.nextMNodeDirection == "<down>")//向下 { IDataReply dataReply = SuperClient.CreateDataReply(para.NodePath.nextMNode); retJson = dataReply.ReplyProcessRequest(para, plugin, controller, method, jsondata); } return(retJson); } catch (Exception err) { throw err; } }
//string ns = "http://www.efwplus.cn/"; public string CreateClient(string clientName) { //客户端回调 IDataReply mCallBack = OperationContext.Current.GetCallbackChannel <IDataReply>(); HeaderParameter para = HeaderOperater.GetHeaderValue(OperationContext.Current.RequestContext.RequestMessage); string ClientID = ClientManage.CreateClient(clientName, DateTime.Now, mCallBack, para.pluginname, para.replyidentify); return(ClientID); }
/// <summary> /// 截获从Client端发送的消息转发到目标终结点并获得返回值给Client端 /// </summary> /// <param name="requestMessage"></param> /// <returns></returns> public Message ProcessMessage(Message requestMessage) { try { begintime(); IRouterService proxy = null; HeaderParameter para = HeaderOperater.GetHeaderValue(requestMessage); if (RouterServerManage.routerDic.ContainsKey(para.routerid)) { proxy = RouterServerManage.routerDic[para.routerid]; para.replyidentify = RouterServerManage.headParaDic[para.routerid].replyidentify; } else { //Binding binding = null; EndpointAddress endpointAddress = null; Uri touri = null; para = RouterServerManage.AddClient(requestMessage, para, out endpointAddress, out touri); requestMessage.Headers.To = touri; IDuplexRouterCallback callback = OperationContext.Current.GetCallbackChannel <IDuplexRouterCallback>(); NetTcpBinding tbinding = new NetTcpBinding("NetTcpBinding_WCFHandlerService"); DuplexChannelFactory <IRouterService> factory = new DuplexChannelFactory <IRouterService>(new InstanceContext(new DuplexRouterCallback(callback)), tbinding, endpointAddress); proxy = factory.CreateChannel(); //缓存会话 RouterServerManage.routerDic.Add(para.routerid, proxy); RouterServerManage.headParaDic.Add(para.routerid, para); } Message responseMessage = null; HeaderOperater.AddMessageHeader(requestMessage, para);//增加自定义消息头 responseMessage = proxy.ProcessMessage(requestMessage); if (para.cmd == "Quit") { //关闭连接释放缓存会话 RouterServerManage.RemoveClient(para); } double outtime = endtime(); // 请求消息记录 if (WcfServerManage.IsDebug) { RouterServerManage.hostwcfMsg(Color.Black, DateTime.Now, String.Format("路由请求消息发送(耗时[" + outtime + "]): {0}", requestMessage.Headers.Action)); } return(responseMessage); } catch (Exception e) { return(Message.CreateMessage(requestMessage.Version, FaultCode.CreateReceiverFaultCode("error", RouterServerManage.ns), e.Message, requestMessage.Headers.Action)); } }
//异步请求 public IAsyncResult BeginProcessRequest(string clientId, string controller, string method, string jsondata, AsyncCallback callback, object asyncState) { string pluginname = null; string cname = null; string[] names = controller.Split(new char[] { '@' }); if (names.Length == 2) { pluginname = names[0]; cname = names[1]; } HeaderParameter para = HeaderOperater.GetHeaderValue(OperationContext.Current.RequestContext.RequestMessage); return(new CompletedAsyncResult <string>(WcfServerManage.ProcessRequest(clientId, pluginname, cname, method, jsondata, para))); }
//服务请求 public string ProcessRequest(string clientId, string controller, string method, string jsondata) { string pluginname = null; string cname = null; string[] names = controller.Split(new char[] { '@' }); if (names.Length == 2) { pluginname = names[0]; cname = names[1]; } HeaderParameter para = HeaderOperater.GetHeaderValue(OperationContext.Current.RequestContext.RequestMessage); return(WcfServerManage.ProcessRequest(clientId, pluginname, cname, method, jsondata, para)); }
public string CreateDomain(string ipAddress) { //客户端回调 IClientService mCallBack = OperationContext.Current.GetCallbackChannel <IClientService>(); HeaderParameter para = HeaderOperater.GetHeaderValue(OperationContext.Current.RequestContext.RequestMessage); string ClientID = WcfServerManage.CreateClient(OperationContext.Current.SessionId, ipAddress, DateTime.Now, mCallBack, para.pluginname, para.replyidentify); //异步执行同步缓存 new Action(delegate() { if (para.pluginname == "SuperPlugin") { //创建连接时候会将上级中间件的缓存同步到下级中间件 DistributedCacheManage.SyncAllCache(mCallBack); } }).BeginInvoke(null, null); return(ClientID); }
/// <summary> /// 获取客户端信息,备用记录日志 /// </summary> public CommonWcfBll() { #region OperationContext context = OperationContext.Current; if (context != null) { //获取客户端请求的路径 string AbsolutePath = context.EndpointDispatcher.EndpointAddress.Uri.AbsolutePath; if (!AbsolutePath.Contains("Com/FrameWork/Helper/Wcf")) { //获取客户端ip和端口 MessageProperties properties = context.IncomingMessageProperties; RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; string client_ip = endpoint.Address; //int client_port = endpoint.Port; //获取客户端请求的契约信息 //string contract_name = context.EndpointDispatcher.ContractName; //获取客户端请求的路径 //Uri request_uri = context.EndpointDispatcher.EndpointAddress.Uri; string sessionid = context.SessionId; string wcfappname = HeaderOperater.GetServiceWcfAppNameHeader(context); wcfappname = wcfappname == null ? "" : wcfappname; context.Channel.Closed += (object sender, EventArgs e) => { //Console.WriteLine(sessionid + "请求结束:" + client_ip + ":" + client_port + "->" + request_uri.AbsolutePath); MonitorData.Instance.UpdateUrlConnNums(client_ip + "_" + wcfappname, AbsolutePath, false); }; //Console.WriteLine(sessionid + "请求开始:" + client_ip + ":" + client_port + "->" + request_uri.AbsolutePath); Hashtable ht = new Hashtable(); ht.Add("ip", client_ip + "_" + wcfappname); ht.Add("url", AbsolutePath); ht.Add("isadd", true); Thread th = new Thread(new ParameterizedThreadStart(Run)); th.Start(ht); } } #endregion }
private void AddMessageHeader(IContextChannel channel, string cmd, bool iscompressjson, bool isencryptionjson, SerializeType serializetype, Action callback) { using (var scope = new OperationContextScope(channel as IContextChannel)) { if (string.IsNullOrEmpty(cmd)) { cmd = ""; } HeaderParameter para = new HeaderParameter(); para.cmd = cmd; para.routerid = mConn.RouterID; para.pluginname = mConn.PluginName; //ReplyIdentify如果客户端创建连接为空,如果中间件连接上级中间件那就是本地中间件标识 para.replyidentify = WcfServerManage.Identify; para.token = mConn.Token; para.iscompressjson = iscompressjson; para.isencryptionjson = isencryptionjson; para.serializetype = serializetype; HeaderOperater.AddMessageHeader(OperationContext.Current.OutgoingMessageHeaders, para); callback(); } }
public string ProcessRequest(string clientId, string plugin, string controller, string method, string jsondata) { HeaderParameter para = HeaderOperater.GetHeaderValue(OperationContext.Current.RequestContext.RequestMessage); return(DataManage.ProcessRequest(clientId, plugin, controller, method, jsondata, para)); }
public IAsyncResult BeginProcessRequest(string clientId, string plugin, string controller, string method, string jsondata, AsyncCallback callback, object asyncState) { HeaderParameter para = HeaderOperater.GetHeaderValue(OperationContext.Current.RequestContext.RequestMessage); return(new CompletedAsyncResult <string>(DataManage.ProcessRequest(clientId, plugin, controller, method, jsondata, para))); }
/// <summary> /// 拦截器处理 /// </summary> /// <param name="msg"></param> /// <returns></returns> public override IMessage Invoke(IMessage msg) { IMethodReturnMessage methodReturn = null; IMethodCallMessage methodCall = (IMethodCallMessage)msg; string contract = typeof(T).FullName; //此处使用wcf连接池技术,获取当前wcf连接池 WcfPool pool = isUseWcfPool ? WcfPoolCache.GetWcfPool(this.server_name) : null; //获取的池子索引 int?index = null; T channel = default(T); OperationContextScope scope = null; if (!isUseWcfPool)//不启用连接池 { ChannelFactory <T> factory = WcfCacheData.GetFactory <T>(this.binging, this.address, this.client.MaxItemsInObjectGraph, this.EnableBinaryFormatterBehavior); channel = factory.CreateChannel(); //scope = new OperationContextScope(((IClientChannel)channel)); } else { #region 统模式 //是否超时 bool isouttime = false; //超时计时器 Stopwatch sw = new Stopwatch(); sw.Start(); while (true) { bool isReap = true; //先判断池子中是否有此空闲连接 if (pool.GetFreePoolNums(contract) > 0) { isReap = false; WcfCommunicationObj commobj = pool.GetChannel <T>(); if (commobj != null) { index = commobj.Index; channel = (T)commobj.CommucationObject; //Console.WriteLine(contract + "获取空闲索引:" + index); } } //如果没有空闲连接判断是否池子是否已满,未满,则创建新连接并装入连接池 if (channel == null && !pool.IsPoolFull) { //创建新连接 ChannelFactory <T> factory = WcfCacheData.GetFactory <T>(this.binging, this.address, this.client.MaxItemsInObjectGraph, this.EnableBinaryFormatterBehavior); //装入连接池 bool flag = pool.AddPool <T>(factory, out channel, out index, isReap); //Console.WriteLine(contract + "装入:" + flag + " 索引:" + index); } //如果当前契约无空闲连接,并且队列已满,并且非当前契约有空闲,则踢掉一个非当前契约 if (channel == null && pool.IsPoolFull && pool.GetFreePoolNums(contract) == 0 && pool.GetUsedPoolNums(contract) != this.wcfMaxPoolSize) { //创建新连接 ChannelFactory <T> factory = WcfCacheData.GetFactory <T>(this.binging, this.address, this.client.MaxItemsInObjectGraph, this.EnableBinaryFormatterBehavior); pool.RemovePoolOneNotAt <T>(factory, out channel, out index); } if (channel != null) { break; } //如果还未获取连接判断是否超时,如果超时抛异常 if (sw.Elapsed >= new TimeSpan(wcfOutTime * 1000 * 10000)) { isouttime = true; break; } else { Thread.Sleep(100); } } sw.Stop(); sw = null; if (isouttime) { throw new Exception("获取连接池中的连接超时,请配置WCF客户端常量配置文件中的WcfOutTime属性,Server name=\"" + server_name + "\""); } #endregion #region 反应器 //AutoResetEvent autoEvents = new AutoResetEvent(false); //BusinessException bex = null; //ThreadPool.QueueUserWorkItem(delegate(object param) //{ // //超时计时器 // Stopwatch sw = new Stopwatch(); // sw.Start(); // while (true) // { // #region while // bool isReap = true; // //先判断池子中是否有此空闲连接 // if (pool.GetFreePoolNums(contract) > 0) // { // isReap = false; // try // { // WcfCommunicationObj commobj = pool.GetChannel<T>(); // if (commobj != null) // { // index = commobj.Index; // channel = (T)commobj.CommucationObject; // } // } // catch (Exception ex) // { // bex = new BusinessException(ex.ToString()); // autoEvents.Set(); // break; // } // } // //如果没有空闲连接判断是否池子是否已满,未满,则创建新连接并装入连接池 // if (channel == null && !pool.IsPoolFull) // { // //创建新连接 // ChannelFactory<T> factory = WcfCacheData.GetFactory<T>(this.binging, this.address, this.client.MaxItemsInObjectGraph,this.EnableBinaryFormatterBehavior); // //装入连接池 // try // { // bool flag = pool.AddPool<T>(factory, out channel, out index, isReap); // } // catch (Exception ex) // { // bex = new BusinessException(ex.ToString()); // autoEvents.Set(); // break; // } // } // //如果当前契约无空闲连接,并且队列已满,并且非当前契约有空闲,则踢掉一个非当前契约 // if (channel == null && pool.IsPoolFull && pool.GetFreePoolNums(contract) == 0 && pool.GetUsedPoolNums(contract) != this.wcfMaxPoolSize) // { // //创建新连接 // ChannelFactory<T> factory = WcfCacheData.GetFactory<T>(this.binging, this.address, this.client.MaxItemsInObjectGraph,this.EnableBinaryFormatterBehavior); // try // { // pool.RemovePoolOneNotAt<T>(factory, out channel, out index); // } // catch (Exception ex) // { // bex = new BusinessException(ex.ToString()); // autoEvents.Set(); // break; // } // } // if (channel != null) // { // autoEvents.Set(); // break; // } // //如果还未获取连接判断是否超时,如果超时抛异常 // if (sw.Elapsed >= new TimeSpan(wcfOutTime * 1000 * 10000)) // { // break; // } // else // { // Thread.Sleep(100); // } // #endregion // } // sw.Stop(); // sw = null; // Thread.CurrentThread.Abort(); //}); //if (!autoEvents.WaitOne(new TimeSpan(wcfOutTime * 1000 * 10000))) //{ // throw new NormalException("获取连接池中的连接超时,请配置WCF客户端常量配置文件中的WcfOutTime属性,Server name=\"" + server_name + "\""); //} //if (bex != null) //{ // throw bex; //} #endregion } #region 递上下文 //web.config或app.config中的ApplicationName string wcfappname = ConfigurationManager.AppSettings["ApplicationName"]; if (wcfappname != null) { HeaderOperater.SetClientWcfAppNameHeader(wcfappname); } #endregion try { object[] copiedArgs = Array.CreateInstance(typeof(object), methodCall.Args.Length) as object[]; methodCall.Args.CopyTo(copiedArgs, 0); object returnValue = methodCall.MethodBase.Invoke(channel, copiedArgs); methodReturn = new ReturnMessage(returnValue, copiedArgs, copiedArgs.Length, methodCall.LogicalCallContext, methodCall); //如果启用连接池,使用完后把连接回归连接池 if (isUseWcfPool) { if (index != null) { pool.ReturnPool <T>((int)index); } } } catch (Exception ex) { var exception = ex; if (ex.InnerException != null) { exception = ex.InnerException; } methodReturn = new ReturnMessage(exception, methodCall); //如果启用连接池,出错则关闭连接,并删除连接池中的连接 if (isUseWcfPool) { if (index != null) { pool.RemovePoolAt <T>((int)index); } } } finally { if (!isUseWcfPool)//不启用连接池 { if (scope != null) { scope.Dispose(); } (channel as IDisposable).Dispose(); } //清除wcf应用程序名上下文 if (wcfappname != null) { HeaderOperater.ClearClientWcfAppNameHeader(); } } return(methodReturn); }
public Message ProcessMessage(Message requestMessage) { try { //计时器 Stopwatch sw = new Stopwatch(); sw.Start(); IRouterBaseHandler proxy = null; HeaderParameter para = HeaderOperater.GetHeaderValue(requestMessage); if (RouterManage.routerDic.ContainsKey(para.routerid)) { proxy = RouterManage.routerDic[para.routerid]; para.replyidentify = RouterManage.headParaDic[para.routerid].replyidentify; } else { //Binding binding = null; EndpointAddress endpointAddress = null; Uri touri = null; para = RouterManage.AddClient(requestMessage, para, out endpointAddress, out touri); requestMessage.Headers.To = touri; IRouterBaseReply callback = OperationContext.Current.GetCallbackChannel <IRouterBaseReply>(); NetTcpBinding tbinding = new NetTcpBinding("NetTcpBinding_BaseService"); DuplexChannelFactory <IRouterBaseHandler> factory = new DuplexChannelFactory <IRouterBaseHandler>(new InstanceContext(new ReplyRouterBaseCallback(callback)), tbinding, endpointAddress); proxy = factory.CreateChannel(); //缓存会话 RouterManage.routerDic.Add(para.routerid, proxy); RouterManage.headParaDic.Add(para.routerid, para); } Message responseMessage = null; try { HeaderOperater.AddMessageHeader(requestMessage, para);//增加自定义消息头 responseMessage = proxy.ProcessMessage(requestMessage); } catch (CommunicationException e) { RouterManage.RemoveClient(para); throw e; } if (para.cmd == "Quit") { //关闭连接释放缓存会话 RouterManage.RemoveClient(para); } //double outtime = endtime(); // 请求消息记录 if (WcfGlobal.IsDebug) { MiddlewareLogHelper.WriterLog(LogType.MidLog, true, Color.Black, String.Format("路由请求消息发送(耗时[" + sw.Elapsed.TotalMilliseconds + "]): {0}", requestMessage.Headers.Action)); } return(responseMessage); } catch (Exception e) { return(Message.CreateMessage(requestMessage.Version, FaultCode.CreateReceiverFaultCode("error", RouterManage.ns), e.Message, requestMessage.Headers.Action)); } }
/// <summary> /// 调用方法前 输出参数值 /// </summary> /// <param name="operationName"></param> /// <param name="inputs"></param> /// <returns></returns> public object BeforeCall(string operationName, object[] inputs) { String guid = Guid.NewGuid().ToString(); try { if (WcfBeforeCallEvent != null) { OperationContext context = OperationContext.Current; string AbsolutePath = ""; if (context != null) { //获取传递的自定义消息头 HeaderContext headercontext = HeaderOperater.GetServiceWcfHeader(context); string wcfappname = HeaderOperater.GetServiceWcfAppNameHeader(context); wcfappname = wcfappname == null ? "" : wcfappname; if (headercontext != null) { guid = headercontext.CorrelationState; } //获取客户端请求的路径 AbsolutePath = context.EndpointDispatcher.EndpointAddress.Uri.AbsolutePath; //获取客户端ip和端口 MessageProperties properties = context.IncomingMessageProperties; RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; string client_ip = endpoint.Address; //int client_port = endpoint.Port; if (!AbsolutePath.Contains("Com/FrameWork/Helper/Wcf")) { Hashtable ht = new Hashtable(); ht.Add("ip", client_ip + "_" + wcfappname); ht.Add("url", AbsolutePath); ht.Add("operatename", operationName); //MonitorData.Instance.UpdateOperateNums(client_ip, AbsolutePath, operationName); Thread th = new Thread(new ParameterizedThreadStart(Run)); th.Start(ht); } } WcfBeforeCallEvent(operationName, inputs, AbsolutePath, guid); #region //Console.WriteLine("返回操作开始:" + AbsolutePath + "/" + operationName); //Console.WriteLine("*************调用操作编号:" + guid.ToString() + "**************"); //for (int i = 0; i < inputs.Length; i++) //{ // Type T = inputs[i].GetType(); // Console.WriteLine("操作参数" + i.ToString() + " 类型为:" + T.ToString()); // Console.WriteLine("操作参数" + i.ToString() + " ToString为:" + inputs[i].ToString()); // Console.WriteLine("操作参数" + i.ToString() + " 属性:"); // PropertyInfo[] PIs = T.GetProperties(); // foreach (PropertyInfo PI in PIs) // { // Console.Write(PI.Name + ":"); // Console.WriteLine(PI.GetValue(inputs[i], null)); // } //} #endregion } } catch { } return(guid); }
/// <summary> /// 拦截器处理 /// </summary> /// <param name="msg"></param> /// <returns></returns> public override IMessage Invoke(IMessage msg) { IMethodReturnMessage methodReturn = null; IMethodCallMessage methodCall = (IMethodCallMessage)msg; string contract = typeof(T).FullName; string server_name = WcfCacheData.GetServerName(contract); WcfClentBinding clientconst = WcfCacheData.GetWcfClientConst(server_name); //web.config或app.config中的ApplicationName string wcfappname = ConfigurationManager.AppSettings["ApplicationName"]; bool EnableBinaryFormatterBehavior = clientconst.EnableBinaryFormatterBehavior; LoadBalanceConfig balance = clientconst.LoadBalance; //获取负载均衡设置中是否启用连接池 bool isUseWcfPool = balance.IsUseWcfPool; //获取负载的服务器uri string uri = null; try { uri = balance.BalanceAlgorithm.GetServerKey(); } catch (Exception buex) { throw buex; } Address uri_address = balance.WcfAdress[uri]; WcfPool pool = null; //获取的池子索引 int?index = null; T channel = default(T); OperationContextScope scope = null; if (!isUseWcfPool)//不启用连接池 { ChannelFactory <T> factory = WcfCacheData.GetFactory <T>(uri_address, EnableBinaryFormatterBehavior); channel = factory.CreateChannel(); //scope = new OperationContextScope(((IClientChannel)channel)); } else { string server_key = server_name + "/" + uri; //初始化连接池 WcfPoolCache.Init(isUseWcfPool, uri_address.WcfMaxPoolSize, balance.WcfOutTime, balance.WcfFailureTime, server_key, balance.WcfPoolMonitorReapTime); //此处使用wcf连接池技术,获取当前wcf连接池 pool = WcfPoolCache.GetWcfPool(server_key); #region 统模式 //是否超时 bool isouttime = false; //超时计时器 Stopwatch sw = new Stopwatch(); sw.Start(); while (true) { #region while if (string.IsNullOrEmpty(uri)) { throw new Exception("所有的负载服务器都挂掉了"); } bool isReap = true; //先判断池子中是否有此空闲连接 if (pool.GetFreePoolNums(contract) > 0) { isReap = false; try { WcfCommunicationObj commobj = pool.GetChannel <T>(); if (commobj != null && commobj.CommucationObject.State == CommunicationState.Opened) { index = commobj.Index; channel = (T)commobj.CommucationObject; } } catch (Exception ex) { throw new Exception(ex.ToString()); } } //如果没有空闲连接判断是否池子是否已满,未满,则创建新连接并装入连接池 if (channel == null && !pool.IsPoolFull) { //创建新连接 ChannelFactory <T> factory = WcfCacheData.GetFactory <T>(uri_address, EnableBinaryFormatterBehavior); //装入连接池 try { bool flag = pool.AddPool <T>(factory, out channel, out index, isReap); } catch (Exception ex) { #region 重新获取服务器 balance.BalanceAlgorithm.Kill(uri); try { uri = balance.BalanceAlgorithm.GetServerKey(); } catch (Exception buex) { throw buex; } uri_address = balance.WcfAdress[uri]; server_key = server_name + "/" + uri; //初始化连接池 WcfPoolCache.Init(isUseWcfPool, uri_address.WcfMaxPoolSize, balance.WcfOutTime, balance.WcfFailureTime, server_key, balance.WcfPoolMonitorReapTime); //此处使用wcf连接池技术,获取当前wcf连接池 pool = WcfPoolCache.GetWcfPool(server_key); continue; #endregion } } //如果当前契约无空闲连接,并且队列已满,并且非当前契约有空闲,则踢掉一个非当前契约 if (channel == null && pool.IsPoolFull && pool.GetFreePoolNums(contract) == 0 && pool.GetUsedPoolNums(contract) != uri_address.WcfMaxPoolSize) { //创建新连接 ChannelFactory <T> factory = WcfCacheData.GetFactory <T>(uri_address, EnableBinaryFormatterBehavior); try { pool.RemovePoolOneNotAt <T>(factory, out channel, out index); } catch (Exception ex) { #region 重新获取服务器 balance.BalanceAlgorithm.Kill(uri); try { uri = balance.BalanceAlgorithm.GetServerKey(); } catch (Exception buex) { throw buex; } uri_address = balance.WcfAdress[uri]; server_key = server_name + "/" + uri; //初始化连接池 WcfPoolCache.Init(isUseWcfPool, uri_address.WcfMaxPoolSize, balance.WcfOutTime, balance.WcfFailureTime, server_key, balance.WcfPoolMonitorReapTime); //此处使用wcf连接池技术,获取当前wcf连接池 pool = WcfPoolCache.GetWcfPool(server_key); continue; #endregion } } if (channel != null) { break; } //如果还未获取连接判断是否超时,如果超时抛异常 if (sw.Elapsed >= new TimeSpan(balance.WcfOutTime * 1000 * 10000)) { break; } else { Thread.Sleep(100); } #endregion } sw.Stop(); sw = null; if (isouttime) { throw new Exception("获取连接池中的连接超时,请配置WCF客户端常量配置文件中的WcfOutTime属性,Server name=\"" + server_name + "\""); } #endregion #region 反应器 //AutoResetEvent autoEvents = new AutoResetEvent(false); //BusinessException bex = null; //ThreadPool.QueueUserWorkItem(delegate(object param) //{ // //超时计时器 // Stopwatch sw = new Stopwatch(); // sw.Start(); // while (true) // { // #region while // if (string.IsNullOrEmpty(uri)) // { // bex = new BusinessException("所有的负载服务器都挂掉了"); // autoEvents.Set(); // break; // } // bool isReap = true; // //先判断池子中是否有此空闲连接 // if (pool.GetFreePoolNums(contract) > 0) // { // isReap = false; // try // { // WcfCommunicationObj commobj = pool.GetChannel<T>(); // if (commobj != null && commobj.CommucationObject.State == CommunicationState.Opened) // { // index = commobj.Index; // channel = (T)commobj.CommucationObject; // } // } // catch (Exception ex) // { // bex = new BusinessException(ex.ToString()); // autoEvents.Set(); // break; // } // } // //如果没有空闲连接判断是否池子是否已满,未满,则创建新连接并装入连接池 // if (channel == null && !pool.IsPoolFull) // { // //创建新连接 // ChannelFactory<T> factory = WcfCacheData.GetFactory<T>(uri_address, EnableBinaryFormatterBehavior); // //装入连接池 // try // { // bool flag = pool.AddPool<T>(factory, out channel, out index, isReap); // } // catch (Exception ex) // { // #region 重新获取服务器 // balance.BalanceAlgorithm.Kill(uri); // try // { // uri = balance.BalanceAlgorithm.GetServerKey(); // } // catch (BusinessException buex) // { // bex = buex; // autoEvents.Set(); // break; // } // uri_address = balance.WcfAdress[uri]; // server_key = server_name + "/" + uri; // //初始化连接池 // WcfPoolCache.Init(isUseWcfPool, uri_address.WcfMaxPoolSize, balance.WcfOutTime, balance.WcfFailureTime, server_key, balance.WcfPoolMonitorReapTime); // //此处使用wcf连接池技术,获取当前wcf连接池 // pool = WcfPoolCache.GetWcfPool(server_key); // continue; // #endregion // } // } // //如果当前契约无空闲连接,并且队列已满,并且非当前契约有空闲,则踢掉一个非当前契约 // if (channel == null && pool.IsPoolFull && pool.GetFreePoolNums(contract) == 0 && pool.GetUsedPoolNums(contract) != uri_address.WcfMaxPoolSize) // { // //创建新连接 // ChannelFactory<T> factory = WcfCacheData.GetFactory<T>(uri_address, EnableBinaryFormatterBehavior); // try // { // pool.RemovePoolOneNotAt<T>(factory, out channel, out index); // } // catch (Exception ex) // { // #region 重新获取服务器 // balance.BalanceAlgorithm.Kill(uri); // try // { // uri = balance.BalanceAlgorithm.GetServerKey(); // } // catch (BusinessException buex) // { // bex = buex; // autoEvents.Set(); // break; // } // uri_address = balance.WcfAdress[uri]; // server_key = server_name + "/" + uri; // //初始化连接池 // WcfPoolCache.Init(isUseWcfPool, uri_address.WcfMaxPoolSize, balance.WcfOutTime, balance.WcfFailureTime, server_key, balance.WcfPoolMonitorReapTime); // //此处使用wcf连接池技术,获取当前wcf连接池 // pool = WcfPoolCache.GetWcfPool(server_key); // continue; // #endregion // } // } // if (channel != null) // { // autoEvents.Set(); // break; // } // //如果还未获取连接判断是否超时,如果超时抛异常 // if (sw.Elapsed >= new TimeSpan(balance.WcfOutTime * 1000 * 10000)) // { // break; // } // else // { // Thread.Sleep(100); // } // #endregion // } // sw.Stop(); // sw = null; // Thread.CurrentThread.Abort(); //}); //if (!autoEvents.WaitOne(new TimeSpan(balance.WcfOutTime * 1000 * 10000))) //{ // throw new NormalException("获取连接池中的连接超时,请配置WCF客户端常量配置文件中的WcfOutTime属性,Server name=\"" + server_name + "\" Uri:" + uri); //} //if (bex != null) //{ // throw bex; //} #endregion } #region 递上下文 if (wcfappname != null) { HeaderOperater.SetClientWcfAppNameHeader(wcfappname); } #endregion try { object[] copiedArgs = Array.CreateInstance(typeof(object), methodCall.Args.Length) as object[]; methodCall.Args.CopyTo(copiedArgs, 0); object returnValue = methodCall.MethodBase.Invoke(channel, copiedArgs); methodReturn = new ReturnMessage(returnValue, copiedArgs, copiedArgs.Length, methodCall.LogicalCallContext, methodCall); //如果启用连接池,使用完后把连接回归连接池 if (isUseWcfPool) { if (index != null && pool != null) { pool.ReturnPool <T>((int)index); } } } catch (Exception ex) { var exception = ex; if (ex.InnerException != null) { exception = ex.InnerException; } methodReturn = new ReturnMessage(exception, methodCall); //如果启用连接池,出错则关闭连接,并删除连接池中的连接 if (isUseWcfPool) { if (index != null && pool != null) { pool.RemovePoolAt <T>((int)index); } } } finally { if (!isUseWcfPool)//不启用连接池 { if (scope != null) { scope.Dispose(); } (channel as IDisposable).Dispose(); } //清除wcf应用程序名上下文 if (wcfappname != null) { HeaderOperater.ClearClientWcfAppNameHeader(); } } return(methodReturn); }