コード例 #1
0
    /// <summary>
    /// Switches the SentinelMasterConnection over to a new primary.
    /// </summary>
    /// <param name="switchBlame">The endpoint responsible for the switch.</param>
    /// <param name="connection">The connection that should be switched over to a new primary endpoint.</param>
    /// <param name="log">The writer to log to, if any.</param>
    internal void SwitchPrimary(EndPoint switchBlame, ConnectionMultiplexer connection, TextWriter log = null)
    {
        if (log == null)
        {
            log = TextWriter.Null;
        }

        using (var logProxy = LogProxy.TryCreate(log))
        {
            string serviceName = connection.RawConfig.ServiceName;

            // Get new primary - try twice
            EndPoint newPrimaryEndPoint = GetConfiguredPrimaryForService(serviceName)
                                          ?? GetConfiguredPrimaryForService(serviceName)
                                          ?? throw new RedisConnectionException(ConnectionFailureType.UnableToConnect,
                                                                                $"Sentinel: Failed connecting to switch primary for service: {serviceName}");

            connection.currentSentinelPrimaryEndPoint = newPrimaryEndPoint;

            if (!connection.servers.Contains(newPrimaryEndPoint))
            {
                EndPoint[] replicaEndPoints = GetReplicasForService(serviceName)
                                              ?? GetReplicasForService(serviceName);

                connection.servers.Clear();
                connection.EndPoints.Clear();
                connection.EndPoints.TryAdd(newPrimaryEndPoint);
                foreach (var replicaEndPoint in replicaEndPoints)
                {
                    connection.EndPoints.TryAdd(replicaEndPoint);
                }
                Trace($"Switching primary to {newPrimaryEndPoint}");
                // Trigger a reconfigure
                connection.ReconfigureAsync(first: false, reconfigureAll: false, logProxy, switchBlame,
                                            $"Primary switch {serviceName}", false, CommandFlags.PreferMaster).Wait();

                UpdateSentinelAddressList(serviceName);
            }
        }
    }