コード例 #1
0
        /// <summary>
        ///     获取部分配置信息
        /// </summary>
        /// <param name="configKey">配置文件KEY名称</param>
        /// <returns>如果不存在指定条件的配置文件,则返回null</returns>
        /// <exception cref="ArgumentNullException">参数不能为空</exception>
        public string GetPartialConfig(string configKey)
        {
            if (string.IsNullOrEmpty(configKey))
            {
                throw new ArgumentNullException("configKey");
            }
            #region Get cache first.

            string config = null;
            //has cache.
            if (_configCaches.TryGetValue(configKey, out config))
            {
                return(config);
            }

            #endregion
            PrepareConnection();
            #region Get remote config.

            CSNGetPartialConfigRequestMessage requestMessage = new CSNGetPartialConfigRequestMessage();
            requestMessage.Key = configKey;
            CSNBusinessMessageTransaction transaction = _transactionManager.Create(IdentityHelper.Create((IPEndPoint)_channel.LocalEndPoint), _channel);
            if (transaction == null)
            {
                throw new Exception("Cannot create a CSN message transaction!");
            }
            AutoResetEvent autoResetEvent = new AutoResetEvent(false);
            transaction.ResponseArrived += delegate(object sender, LightSingleArgEventArgs <BaseMessage> e)
            {
                CSNGetPartialConfigResponseMessage rspMsg = (CSNGetPartialConfigResponseMessage)e.Target;
                if (rspMsg.ErrorId == 0 && !string.IsNullOrEmpty(rspMsg.Config))
                {
                    //add cache.
                    _configCaches[configKey] = rspMsg.Config;
                    config = rspMsg.Config;
                }
                autoResetEvent.Set();
            };
            transaction.Failed += delegate
            {
                _transactionManager.Remove(transaction.Identity);
                autoResetEvent.Set();
            };
            transaction.Timeout += delegate
            {
                _transactionManager.Remove(transaction.Identity);
                autoResetEvent.Set();
            };
            transaction.SendRequest(requestMessage);
            //wait 35s.
            autoResetEvent.WaitOne(35000);
            autoResetEvent.Dispose();
            return(config);

            #endregion
        }
コード例 #2
0
        /// <summary>
        ///     创建一个新的事务
        /// </summary>
        /// <param name="role">针对的服务角色</param>
        /// <param name="userId">需要定位的用户编号</param>
        /// <returns>返回新的事务</returns>
        /// <exception cref="ArgumentNullException">参数不能为空</exception>
        public BusinessMessageTransaction CreateTransaction(string role, int userId)
        {
            if (string.IsNullOrEmpty(role))
            {
                throw new ArgumentNullException("role");
            }
            string errMsg;
            IServerConnectionAgent <BaseMessage> agent = _clsuter.GetChannelBySpecificCondition(role, _protocolStacks[role], userId, out errMsg);

            return(agent == null
                       ? new FailMobiSageMessageTransaction(errMsg)
                       : _transactionManager.Create(IdentityHelper.Create((IPEndPoint)agent.GetChannel().LocalEndPoint), agent.GetChannel()));
        }
コード例 #3
0
        /// <summary>
        ///     创建一个新的事务
        /// </summary>
        /// <param name="role">针对的服务角色</param>
        /// <returns>返回新的事务</returns>
        /// <exception cref="ArgumentNullException">参数不能为空</exception>
        public MetadataMessageTransaction CreateMetadataTransaction(string role)
        {
            if (string.IsNullOrEmpty(role))
            {
                throw new ArgumentNullException("role");
            }
            string errMsg;
            IServerConnectionAgent <MetadataContainer> agent = _metadataCluster.GetChannel(role, _metadataProtocolStack, out errMsg);

            return(agent == null
                       ? new FailMobiSageMetadataTransaction(errMsg)
                       : _metadataTransactionManager.Create(IdentityHelper.Create((IPEndPoint)agent.GetChannel().LocalEndPoint), agent.GetChannel()));
        }
コード例 #4
0
        /// <summary>
        ///     创建一个新的消息事务,并将其加入到当前的事务列表中
        /// </summary>
        /// <param name="sequenceId">本次新事务的唯一编号</param>
        /// <param name="channel">消息通信信道</param>
        /// <returns>返回一个新的消息事务</returns>
        /// <exception cref="ArgumentNullException">通信信道不能为空</exception>
        public ThriftMessageTransaction Create(int sequenceId, IMessageTransportChannel <ThriftMessage> channel)
        {
            if (channel == null)
            {
                throw new ArgumentNullException("channel");
            }
            ThriftMessageTransaction transaction = new ThriftMessageTransaction(new Lease(DateTime.MaxValue), channel)
            {
                TransactionManager = this, SequenceId = sequenceId
            };
            TransactionIdentity identity = IdentityHelper.Create((IPEndPoint)channel.LocalEndPoint, sequenceId, false);

            transaction.Identity = identity;
            return(Add(transaction) ? transaction : null);
        }
コード例 #5
0
        //new message arrived.
        void ChannelReceivedMessage(object sender, LightSingleArgEventArgs <System.Collections.Generic.List <ThriftMessage> > e)
        {
            IMessageTransportChannel <ThriftMessage> msgChannel = (IMessageTransportChannel <ThriftMessage>)sender;

            foreach (ThriftMessage message in e.Target)
            {
                if (message == null)
                {
                    continue;
                }
                _tracing.Info("L: {0}\r\nR: {1}\r\n{2}", msgChannel.LocalEndPoint, msgChannel.RemoteEndPoint, message.ToString());
                //rebuilds corresponding TransactionIdentity for current RSP message.
                TransactionIdentity identity = IdentityHelper.Create((IPEndPoint)msgChannel.LocalEndPoint, (int)message.Identity.SequenceId, false);
                _transactionManager.Active(identity, message);
            }
        }
コード例 #6
0
        /// <summary>
        ///     创建一个新的事务
        ///     <para>* 按照固定手机号的负载策略</para>
        /// </summary>
        /// <param name="targetRole">针对的服务角色</param>
        /// <param name="protocolSelf">使用的协议栈</param>
        /// <param name="mobileNo">手机号</param>
        /// <returns>返回新的事务</returns>
        /// <exception cref="ArgumentNullException">参数不能为空</exception>
        public BusinessMessageTransaction CreateTransaction(string targetRole, string protocolSelf, long mobileNo)
        {
            if (string.IsNullOrEmpty(targetRole))
            {
                throw new ArgumentNullException("targetRole");
            }
            if (string.IsNullOrEmpty(protocolSelf))
            {
                throw new ArgumentNullException("protocolSelf");
            }
            string errMsg;
            IServerConnectionAgent <BaseMessage> agent = _clsuter.GetChannelBySpecificCondition(targetRole, _protocolStacks[protocolSelf], mobileNo, out errMsg);

            return(agent == null
                       ? new FailMobiSageMessageTransaction(errMsg)
                       : _transactionManager.Create(IdentityHelper.Create((IPEndPoint)agent.GetChannel().LocalEndPoint), agent.GetChannel()));
        }
コード例 #7
0
        /// <summary>
        ///     获取指定表的数据
        /// </summary>
        /// <param name="database">数据库名</param>
        /// <param name="table">表名</param>
        /// <param name="hasCache">缓存标识</param>
        /// <returns>返回表数据</returns>
        /// <exception cref="ArgumentNullException">参数不能为空</exception>
        public DataTable GetTable(string database, string table, bool hasCache)
        {
            DataTable result    = null;
            Exception exception = null;

            if (hasCache)
            {
                //get cache by default.
                if ((result = GetCacheTable(string.Format("{0}.{1}", database, table))) != null)
                {
                    return(result);
                }
            }
            PrepareConnection();
            CSNGetDataTableRequestMessage requestMessage = new CSNGetDataTableRequestMessage();

            requestMessage.DatabaseName = database;
            requestMessage.TableName    = table;
            CSNBusinessMessageTransaction transaction = _transactionManager.Create(IdentityHelper.Create((IPEndPoint)_channel.LocalEndPoint), _channel);

            if (transaction == null)
            {
                throw new Exception("Cannot create a CSN message transaction!");
            }
            AutoResetEvent autoResetEvent = new AutoResetEvent(false);

            transaction.ResponseArrived += delegate(object sender, LightSingleArgEventArgs <BaseMessage> e)
            {
                CSNGetDataTableResponseMessage responseMessage = (CSNGetDataTableResponseMessage)e.Target;
                result = responseMessage.Tables == null ? null : responseMessage.Tables;
                autoResetEvent.Set();
            };
            transaction.Failed += delegate
            {
                _transactionManager.Remove(transaction.Identity);
                exception = new Exception("Failed! Cannot get table data config from CSN service, #table: " + table);
                autoResetEvent.Set();
            };
            transaction.Timeout += delegate
            {
                _transactionManager.Remove(transaction.Identity);
                exception = new Exception("Timeout! Cannot get table data config from CSN service, #table: " + table);
                autoResetEvent.Set();
            };
            transaction.SendRequest(requestMessage);
            //wait 35s.
            autoResetEvent.WaitOne(35000);
            autoResetEvent.Dispose();
            if (exception != null)
            {
                throw exception;
            }
            #region Add table cahce.

            if (hasCache && result != null)
            {
                lock (_lockTablesObj)
                    _cacheTables.Add(string.Format("{0}.{1}", database, table), result);
            }

            #endregion
            return(result);
        }
コード例 #8
0
        /// <summary>
        ///     获取某个字段的值
        /// </summary>
        /// <typeparam name="T">字段类型</typeparam>
        /// <param name="database">数据库名</param>
        /// <param name="table">表名</param>
        /// <param name="service">服务名称</param>
        /// <param name="field">字段名</param>
        /// <returns>返回相应字段的值</returns>
        /// <exception cref="ArgumentNullException">参数不能为空</exception>
        public string GetField(string database, string table, string service, string field)
        {
            string result = null;

            #region Get cache first.

            Dictionary <string, string> items;
            //has cache.
            if (_cacheKeys.TryGetValue(service, out items))
            {
                return(items.TryGetValue(field, out result) ? result : null);
            }

            #endregion
            PrepareConnection();
            #region Get remote config.

            Exception exception = null;
            CSNGetKeyDataRequestMessage requestMessage = new CSNGetKeyDataRequestMessage();
            requestMessage.DatabaseName = database;
            requestMessage.TableName    = table;
            requestMessage.ServiceName  = service;

            CSNBusinessMessageTransaction transaction = _transactionManager.Create(IdentityHelper.Create((IPEndPoint)_channel.LocalEndPoint), _channel);
            if (transaction == null)
            {
                throw new Exception("Cannot create a CSN message transaction!");
            }
            AutoResetEvent autoResetEvent = new AutoResetEvent(false);
            transaction.ResponseArrived += delegate(object sender, LightSingleArgEventArgs <BaseMessage> e)
            {
                CSNGetKeyDataResponseMessage rspMessage = (CSNGetKeyDataResponseMessage)e.Target;
                #region Add Cache.

                Dictionary <string, string> values = new Dictionary <string, string>();
                if (rspMessage.Items != null)
                {
                    foreach (KeyValueItem item in rspMessage.Items)
                    {
                        values.Add(item.Key, item.Value);
                    }
                    _cacheKeys.Add(service, values);
                }
                //get result.
                result = values.ContainsKey(field) ? values[field] : null;

                #endregion
                autoResetEvent.Set();
            };
            transaction.Failed += delegate
            {
                _transactionManager.Remove(transaction.Identity);
                exception = new Exception("Failed! Cannot get key data config from CSN service, #key: " + field);
                autoResetEvent.Set();
            };
            transaction.Timeout += delegate
            {
                _transactionManager.Remove(transaction.Identity);
                exception = new Exception("Timeout! Cannot get key data config from CSN service, #key: " + field);
                autoResetEvent.Set();
            };
            transaction.SendRequest(requestMessage);
            //wait 35s.
            autoResetEvent.WaitOne(35000);
            autoResetEvent.Dispose();
            if (exception != null)
            {
                throw exception;
            }

            #endregion

            return(result);
        }
コード例 #9
0
        /// <summary>
        ///     创建一个新的网络事务
        /// </summary>
        /// <param name="appName">目标APP的名称</param>
        /// <param name="target">标示网络终点接的协议簇组合</param>
        /// <param name="maximumRspTime">等待当前网络事务RSP消息的最大时间</param>
        /// <param name="resourceUri">KAE资源URI</param>
        /// <param name="balanceFlag">负载标识</param>
        /// <param name="communicationType">通信方式</param>
        /// <param name="version">
        ///     目标APP的版本
        ///     <para>* 默认为: latest</para>
        /// </param>
        /// <param name="protocolSelf">
        ///     使用的协议栈的角色
        ///     <para>* 如果当前事务代理器所承载的消息协议为MetadataContainer时请忽略此参数</para>
        /// </param>
        /// <returns>返回新的事务</returns>
        public IMessageTransaction <TMessage> CreateTransaction(string appName, Protocols target, TimeSpan maximumRspTime, long balanceFlag, string version = "latest", KAEResourceUri resourceUri = null, NetworkCommunicationTypes communicationType = NetworkCommunicationTypes.Dulplex, string protocolSelf = null)
        {
            if (string.IsNullOrEmpty(appName))
            {
                throw new ArgumentNullException("appName");
            }
            string           errMsg;
            ApplicationLevel level = (resourceUri == null ? ApplicationLevel.Stable : _callback(resourceUri));
            KAERingNode      ringNode;
            IServerConnectionAgent <TMessage> agent = _cluster.GetChannel(target, level, _container.GetDefaultProtocolStack(_cluster.ProtocolType), balanceFlag, out errMsg, out ringNode);

            if (agent == null)
            {
                lock (_lockObj)
                {
                    //try to obtains agent object again for ensuring that the newest remoting addresses can be appliy in the multiple threading env.
                    agent = _cluster.GetChannel(target, level, _container.GetDefaultProtocolStack(_cluster.ProtocolType), balanceFlag, out errMsg, out ringNode);
                    if (agent == null && !GetMissedRemoteAddresses(appName, version, target, level))
                    {
                        return(new FailMessageTransaction <TMessage>(errMsg));
                    }
                    agent = _cluster.GetChannel(target, level, _container.GetDefaultProtocolStack(_cluster.ProtocolType), balanceFlag, out errMsg, out ringNode);
                    //check returned value again for avoiding couldnt connect to the remote address now.
                    if (agent == null)
                    {
                        return(new FailMessageTransaction <TMessage>(errMsg));
                    }
                }
            }
            MessageTransaction <TMessage> transaction = NewTransaction(new Lease(DateTime.Now.Add(maximumRspTime)), agent.GetChannel());

            transaction.SetMessageIdentity(new MessageIdentity {
                ProtocolId = (byte)target.ProtocolId, ServiceId = (byte)target.ServiceId, DetailsId = (byte)target.DetailsId
            });
            transaction.TransactionManager = _transactionManager;
            transaction.Identity           = (communicationType == NetworkCommunicationTypes.Dulplex ? IdentityHelper.Create(agent.GetChannel().LocalEndPoint, TransportChannelTypes.TCP) : IdentityHelper.CreateOneway(agent.GetChannel().LocalEndPoint, TransportChannelTypes.TCP));
            transaction.KPPUniqueId        = ringNode.KPPUniqueId;
            return(_transactionManager.Add(transaction.Identity, transaction) ? transaction : null);
        }
コード例 #10
0
 /// <summary>
 ///     虚拟的消息事物,仅用于单元测试中使用
 /// </summary>
 public FakedBusinessTransaction()
 {
     Identity = IdentityHelper.Create(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 10000));
 }
コード例 #11
0
 /// <summary>
 ///     创建一个新的事务
 /// </summary>
 /// <returns>返回新创建的事务</returns>
 /// <exception cref="ArgumentNullException">参数错误</exception>
 public MessageTransaction <BaseMessage> CreateTransaction()
 {
     return(_transactionManager.Create(IdentityHelper.Create(_channel.LocalEndPoint, _channel.ChannelType), _channel));
 }
コード例 #12
0
 /// <summary>
 ///     创建一个新的事务
 /// </summary>
 /// <returns>返回新创建的事务</returns>
 /// <exception cref="ArgumentNullException">参数错误</exception>
 public MessageTransaction <MetadataContainer> CreateTransaction()
 {
     return(_transactionManager.Create(IdentityHelper.Create(_channel.LocalEndPoint, _channel.ChannelType), _channel));
 }