public SoapTcpConnection(WebCrawlerConnection connectionString) : this() { this.IPAddress = connectionString.Address; this.Port = connectionString.Port; this.TimeOut = connectionString.TimeOut; this.Pooling = connectionString.Pooling; this.PoolingMinSize = connectionString.PoolingMinSize; this.PoolingMaxSize = connectionString.PoolingMaxSize; }
/// <summary> /// 初始化连接池 /// </summary> public void ConfigPool(WebCrawlerConnection config) { if (null == config && !config.IsValidConfig()) { return; } _config = config; try { this.CreatOneConnectionToPool(_config.Pooling, _config.PoolingMinSize); } catch (Exception ex) { throw ex; } }
/// <summary> /// 获取制定连接配置的连接池 /// </summary> /// <param name="config"></param> /// <returns></returns> public static SoapTcpPool GetPool(WebCrawlerConnection config) { SoapTcpPool _pool = null; var key = config.ToString(); if (_poolManager.ContainsKey(key)) { _pool = _poolManager[key]; return(_pool); } //如果字典没有池 那么创建池对象 _pool = new SoapTcpPool(); _pool.ConfigPool(config); if (!_poolManager.ContainsKey(key)) { _poolManager.TryAdd(key, _pool); } return(_pool); }
/// <summary> /// 关闭连接 /// </summary> public void Close() { if (this.State != ConnectionState.Closed && driver != null) { //扔回连接池中 var currentSettings = new WebCrawlerConnection { Address = this.IPAddress, Port = this.Port }; SoapTcpPool pool = SoapTcpPool.GetPool(currentSettings); if (null != pool) { pool.ReleaseToPool(this.driver); this.driver = null; } else { this.driver.Close();//如果没有在池中 那么直接关闭对象 } } }
/// <summary> /// 打开连接 /// </summary> public void Open() { if (null != this.driver && State == ConnectionState.Open) { return; } try { var currentSettings = new WebCrawlerConnection { Address = this.IPAddress, Port = this.Port, TimeOut = this.TimeOut, Pooling = this.Pooling, PoolingMinSize = this.PoolingMinSize, PoolingMaxSize = this.PoolingMaxSize, }; SoapTcpPool pool = SoapTcpPool.GetPool(currentSettings); if (null != pool) { driver = pool.GetConnection(); } if (driver == null) { driver = SoapTcpPool.CreatNewConnection(this.IPAddress, this.Port, this.Pooling, this.PoolingMinSize); } if (!driver.Connected) { driver.Connect(this.TimeOut * 1000); } this.State = ConnectionState.Open; } catch (Exception ex) { this.State = ConnectionState.Closed; throw ex; } }