コード例 #1
0
        /// <summary>
        /// Gets a connection to a random member.
        /// </summary>
        /// <returns>A random client connection if available; otherwise <c>null</c>.</returns>
        public MemberConnection GetRandomConnection()
        {
            MemberConnection connection;

            // In "smart routing" mode the clients connect to each member of the cluster. Since each
            // data partition uses the well known and consistent hashing algorithm, each client
            // can send an operation to the relevant cluster member, which increases the
            // overall throughput and efficiency. Smart mode is the default mode.
            //
            // In "uni-socket" mode the clients is required to connect to a single member, which
            // then behaves as a gateway for the other members. Firewalls, security, or some
            // custom networking issues can be the reason for these cases.

            if (_clusterState.IsSmartRouting)
            {
                // "smart" mode

                // limit the number of tries to the amount of known members
                var count = _loadBalancer.Count;

                for (var i = 0; i < count; i++)
                {
                    var memberId = _loadBalancer.GetMember();
                    lock (Mutex)
                    {
                        if (_connections.TryGetValue(memberId, out connection))
                        {
                            return(connection);
                        }
                    }
                }
            }

            // either "smart" mode but the load balancer did not return a member,
            // or "uni-socket" mode where there should only be once connection
            lock (Mutex) connection = _connections.Values.FirstOrDefault();

            // may be null
            return(connection);
        }