201b01b16b071839fa43e546f653b9bceb2e7bb4.svn-base 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. using System;
  2. using System.IO;
  3. using System.Xml;
  4. using System.Data;
  5. using System.Text;
  6. using System.Collections;
  7. using System.Reflection;
  8. using System.Configuration;
  9. using Core.Mes.Common;
  10. using Core.Mes.IBaseInterface;
  11. namespace Core.Mes.ServerFrameWork
  12. {
  13. public class Dispatcher : MarshalByRefObject, ICommon
  14. {
  15. private ServerConfigure _servConf = null;
  16. public ServerConfigure ServConfig
  17. {
  18. get { return _servConf; }
  19. }
  20. #region " Construct "
  21. public Dispatcher() { }
  22. public Dispatcher(IServerPool pool, ServerConfigure _conf)
  23. {
  24. Pool = pool;
  25. _servConf = _conf;
  26. }
  27. private IServerPool _pool = null;
  28. public IServerPool Pool
  29. {
  30. get { return _pool; }
  31. set { _pool = value; }
  32. }
  33. #endregion
  34. #region " Variable "
  35. //== 子服务集合
  36. public static Hashtable _htServers = new Hashtable();
  37. //== 数据链接集合
  38. public static Hashtable htDBManager = new Hashtable();
  39. public event GetStatusInfoHandler getStatusInfo;
  40. public delegate void GetStatusInfoHandler(string info);
  41. protected virtual void SetStatusMessage(string info)
  42. {
  43. if (getStatusInfo != null)
  44. {
  45. getStatusInfo(info);
  46. }
  47. }
  48. #endregion
  49. #region 内存释放
  50. public void MemoryDispose()
  51. {
  52. long memorysize = System.Diagnostics.Process.GetCurrentProcess().WorkingSet64;
  53. int PagedMemorySize = (int)memorysize / (1024 * 1024);
  54. if (PagedMemorySize > _servConf.MemoryMaxSize)//进程占用内存>100M 做GC.
  55. {
  56. try
  57. {
  58. GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
  59. }
  60. catch
  61. {
  62. }
  63. System.Diagnostics.Process.GetCurrentProcess().Dispose();
  64. }
  65. }
  66. #endregion
  67. #region MethodTimeLog
  68. private static object lockObj = new object();
  69. public void MethodTimeLog(TimeSpan tspan, object[] objs, object[] args)
  70. {
  71. string path = string.Format(@"./log/Method/MethodTimeLog_{0}.txt", System.DateTime.Now.ToString("yyyy_MM_dd"));
  72. lock (lockObj)
  73. {
  74. using (StreamWriter sw = new StreamWriter(path, true, Encoding.UTF8))
  75. {
  76. StringBuilder sbtxt = new StringBuilder();
  77. sbtxt.AppendLine("==============================================");
  78. sbtxt.AppendLine(string.Format("LogWriteTime:{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
  79. sbtxt.AppendLine(string.Format("Time:{0}", tspan.TotalMilliseconds));
  80. sbtxt.AppendLine(string.Format("ClassName:{0}", objs[0].ToString()));
  81. sbtxt.AppendLine(string.Format("MethodName:{0}", objs[1].ToString()));
  82. if (args != null)
  83. {
  84. foreach (object obj in args)
  85. {
  86. if (obj != null)
  87. {
  88. sbtxt.AppendLine(string.Format("Parameters:{0}", obj.ToString()));
  89. }
  90. }
  91. }
  92. sbtxt.AppendLine("==============================================");
  93. sw.WriteLine(sbtxt.ToString());
  94. }
  95. }
  96. }
  97. public void MethodErrLog(Exception ex, object[] objs, object[] args)
  98. {
  99. string path = string.Format(@"./log/Method/MethodErrLog_{0}.txt", System.DateTime.Now.ToString("yyyy_MM_dd"));
  100. lock (lockObj)
  101. {
  102. using (StreamWriter sw = new StreamWriter(path, true, Encoding.UTF8))
  103. {
  104. StringBuilder sbtxt = new StringBuilder();
  105. sbtxt.AppendLine("==============================================");
  106. sbtxt.AppendLine(string.Format("LogWriteTime:{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
  107. sbtxt.AppendLine(string.Format("ClassName:{0}", objs[0].ToString()));
  108. sbtxt.AppendLine(string.Format("MethodName:{0}", objs[1].ToString()));
  109. if (args != null)
  110. {
  111. foreach (object obj in args)
  112. {
  113. if (obj != null)
  114. {
  115. sbtxt.AppendLine(string.Format("Parameters:{0}", obj.ToString()));
  116. }
  117. }
  118. }
  119. sbtxt.AppendLine(ex.Message);
  120. sbtxt.AppendLine(ex.StackTrace);
  121. sbtxt.AppendLine("==============================================");
  122. sw.WriteLine(sbtxt.ToString());
  123. }
  124. }
  125. }
  126. public void DebugLog(object[] objs, object[] args)
  127. {
  128. string path = string.Format(@"./log/Method/DebugLog_{0}.txt", System.DateTime.Now.ToString("yyyy_MM_dd"));
  129. lock (lockObj)
  130. {
  131. if (File.Exists(Path.GetFullPath(path)))
  132. {
  133. FileInfo fileInfo = new FileInfo(Path.GetFullPath(path));
  134. if (fileInfo.Length / (1024 * 1024) > 6)
  135. {
  136. File.Delete(path);
  137. }
  138. }
  139. using (StreamWriter sw = new StreamWriter(path, true, Encoding.UTF8))
  140. {
  141. StringBuilder sbtxt = new StringBuilder();
  142. sbtxt.AppendLine("==============================================");
  143. sbtxt.AppendLine(string.Format("LogWriteTime:{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
  144. sbtxt.AppendLine(string.Format("ClassName:{0}", objs[0].ToString()));
  145. sbtxt.AppendLine(string.Format("MethodName:{0}", objs[1].ToString()));
  146. if (args != null)
  147. {
  148. foreach (object obj in args)
  149. {
  150. if (obj != null)
  151. {
  152. sbtxt.AppendLine(string.Format("Parameters:{0}", obj.ToString()));
  153. }
  154. }
  155. }
  156. sbtxt.AppendLine("==============================================");
  157. sw.WriteLine(sbtxt.ToString());
  158. }
  159. }
  160. }
  161. #endregion
  162. #region " 调用服务 "
  163. /// <summary>
  164. /// 服务端公开给客户端的调用后台服务的方法
  165. /// </summary>
  166. /// <param name="message"></param>
  167. /// <returns></returns>
  168. public ReturnObject MethodHandler(CallingMessage message, ValidateInfo validateInfo)
  169. {
  170. CallingMessageEx messageEx = new CallingMessageEx();
  171. messageEx.FromCallingMessage(message);
  172. messageEx.RedirectLimit = 0;
  173. messageEx.InnerServerRedirect = true;
  174. ReturnObjectEx rtnObjEx = Execute(messageEx, validateInfo);
  175. ReturnObject rtnObj = new ReturnObject();
  176. rtnObj.ErrCode = rtnObjEx.ErrCode;
  177. rtnObj.ErrMessage = rtnObjEx.ErrMessage;
  178. rtnObj.RealDataSet = rtnObjEx.RealDataSet;
  179. rtnObj.RealObject = rtnObjEx.RealObject;
  180. return rtnObj;
  181. }
  182. public ReturnObjectEx MethodHandlerEx(CallingMessageEx message, ValidateInfo validateInfo)
  183. {
  184. return Execute(message, validateInfo);
  185. }
  186. private ReturnObjectEx Execute(CallingMessageEx messageEx, ValidateInfo validateInfo)
  187. {
  188. //step1:
  189. MemoryDispose();
  190. //step2:
  191. string serverName = messageEx.ServerName;
  192. string assemblyName = messageEx.AssemblyName;
  193. string className = messageEx.ClassName;
  194. string methodName = messageEx.MethodName;
  195. object[] args = messageEx.args;
  196. ReturnObjectEx rtnObjEx = new ReturnObjectEx();
  197. MethodInfo myMethod = null;
  198. try
  199. {
  200. if (Pool.HtComponent.Contains(className))
  201. {
  202. try
  203. {
  204. if (serverName.ToUpper() != "SERVERCOMMON" && messageEx.RedirectLimit > 0)
  205. {
  206. string RedirURL = "";
  207. double sum_factor = 0;
  208. ArrayList serviceProvider = new ArrayList();
  209. ArrayList pfactors = new ArrayList();
  210. serviceProvider.Add("THIS");
  211. sum_factor += this.ServConfig.PriorityFactor;
  212. pfactors.Add(sum_factor);
  213. foreach (string server in Pool.HtExtServer.Keys)
  214. {
  215. RemotingServer rs = (RemotingServer)Pool.HtExtServer[server];
  216. if (rs.Valid != RemoteServerStatus.Normal || rs.Enable == false) continue;
  217. rs.FindRemoteServer(serverName);
  218. if (!rs.HTServices.ContainsKey(serverName)) continue;
  219. ServiceObject so = ((ServiceObject)(rs.HTServices[serverName]));
  220. if (so.Valid != ServiceObjectStatus.Normal || so.Enable == false) continue;
  221. RedirURL = so.URL;
  222. sum_factor += rs.PriorityFactor;
  223. serviceProvider.Add(server);
  224. pfactors.Add(sum_factor);
  225. }
  226. Random rand = new Random();
  227. double rand_selector = rand.NextDouble() * sum_factor;
  228. int selector = 0;
  229. for (int idx = 0; idx < pfactors.Count; idx++)
  230. {
  231. if (rand_selector <= (double)pfactors[idx])
  232. {
  233. selector = idx;
  234. break;
  235. }
  236. }
  237. if (selector != 0)
  238. {
  239. SimpleReturnObject _out = new SimpleReturnObject();
  240. if (messageEx.InnerServerRedirect)
  241. {
  242. RemotingServer rs = (RemotingServer)Pool.HtExtServer[serviceProvider[selector]];
  243. rtnObjEx = (ReturnObjectEx)rs.ExecuteMethod(messageEx, out _out);
  244. return rtnObjEx;
  245. }
  246. else
  247. {
  248. rtnObjEx.ReDirectURL = RedirURL;
  249. return rtnObjEx;
  250. }
  251. }
  252. }
  253. //使用本地服务
  254. myMethod = Pool.GetType().GetMethod("HandleMethod");
  255. DateTime startTime = DateTime.Now;
  256. if (_servConf.Debug == "true")
  257. {
  258. DebugLog(new object[] { className, methodName }, args);
  259. }
  260. ReturnObject rtnObj = (ReturnObject)myMethod.Invoke(Pool, new object[] { className, methodName, args });
  261. rtnObjEx.ReDirectURL = "";
  262. rtnObjEx.ErrCode = rtnObj.ErrCode;
  263. rtnObjEx.ErrMessage = rtnObj.ErrMessage;
  264. rtnObjEx.RealDataSet = rtnObj.RealDataSet;
  265. rtnObjEx.RealObject = rtnObj.RealObject;
  266. DateTime endTime = DateTime.Now;
  267. TimeSpan tspan = endTime - startTime;
  268. if (tspan.TotalMilliseconds > (_servConf.MethodTime * 1000))
  269. {
  270. MethodTimeLog(tspan, new object[] { className, methodName }, args);
  271. }
  272. if (rtnObjEx.RealObject != null)
  273. {
  274. if (rtnObjEx.RealObject.GetType() == typeof(DataSet))
  275. {
  276. DataSet _ds = (DataSet)rtnObjEx.RealObject;
  277. bool largeData = false;
  278. int row_cnt = 0;
  279. foreach (DataTable _dt in _ds.Tables)
  280. {
  281. row_cnt += _dt.Rows.Count;
  282. if (_dt.Rows.Count > _servConf.CompressThreshold || row_cnt > _servConf.CompressThreshold)
  283. {
  284. largeData = true;
  285. break;
  286. }
  287. }
  288. if (largeData)
  289. {
  290. byte[] _rtn = Utility.SerializeDataSet(_ds);
  291. byte[] _rtn_comp = Utility.CompressBytes(_rtn);
  292. DataTable dt_rus = new DataTable("RETURN_RESULT");
  293. dt_rus.Columns.AddRange(new DataColumn[]{
  294. new DataColumn("IsCompressed", System.Type.GetType("System.Int32") ),
  295. new DataColumn("UnCompress_size", System.Type.GetType("System.Int32")),
  296. new DataColumn("Compress_size", System.Type.GetType("System.Int32"))}
  297. );
  298. dt_rus.AcceptChanges();
  299. dt_rus.Rows.Add(new object[] { 1, _rtn.Length, _rtn_comp.Length });
  300. dt_rus.AcceptChanges();
  301. if (rtnObjEx.RealDataSet == null)
  302. {
  303. rtnObjEx.RealDataSet = new DataSet();
  304. }
  305. rtnObjEx.RealDataSet.Tables.Add(dt_rus);
  306. rtnObjEx.RealObject = _rtn_comp;
  307. }
  308. }
  309. }
  310. return rtnObjEx;
  311. }
  312. catch (Exception ex)
  313. {
  314. MethodErrLog(ex, new object[] { className, methodName }, args);
  315. return new ReturnObjectEx(null, ex.Message);
  316. }
  317. finally
  318. {
  319. //if (myMethod != null) myMethod = null;
  320. try
  321. {
  322. if (rtnObjEx.RealObject != null)
  323. {
  324. rtnObjEx.RealObject = null;
  325. }
  326. if (rtnObjEx.RealDataSet != null)
  327. {
  328. rtnObjEx.RealDataSet = null;
  329. }
  330. }
  331. catch { }
  332. }
  333. }
  334. else
  335. {
  336. return new ReturnObjectEx(null, "未找到请求的服务![2]");
  337. }
  338. }
  339. catch (Exception ex)
  340. {
  341. return new ReturnObjectEx(null, "服务调用发生异常! \n" + ex.Message);
  342. }
  343. }
  344. #endregion
  345. #region " Common Handler "
  346. //=======================================================
  347. // 用来确保当创建 Singleton 时, 第一个实例永远不会过期
  348. //=======================================================
  349. public override object InitializeLifetimeService()
  350. {
  351. return null;
  352. }
  353. #endregion
  354. }
  355. }