/// <summary>
        /// Assigns a new server driver to the connection object
        /// </summary>
        /// <param name="groupName">Group name</param>
        /// <param name="master">True if the server connection to assign must be a master</param>
        /// <param name="connection">MySqlConnection object where the new driver will be assigned</param>
        internal static void GetNewConnection(string groupName, bool master, MySqlConnection connection)
        {
            do
            {
                lock (thisLock)
                {
                    if (!IsReplicationGroup(groupName))
                    {
                        return;
                    }

                    ReplicationServerGroup group  = GetGroup(groupName);
                    ReplicationServer      server = group.GetServer(master, connection.Settings);

                    if (server == null)
                    {
                        throw new MySqlException(Properties.Resources.Replication_NoAvailableServer);
                    }

                    try
                    {
                        bool isNewServer = false;
                        if (connection.driver == null || !connection.driver.IsOpen)
                        {
                            isNewServer = true;
                        }
                        else
                        {
                            MySqlConnectionStringBuilder msb = new MySqlConnectionStringBuilder(server.ConnectionString);
                            if (!msb.Equals(connection.driver.Settings))
                            {
                                isNewServer = true;
                            }
                        }
                        if (isNewServer)
                        {
                            Driver driver = Driver.Create(new MySqlConnectionStringBuilder(server.ConnectionString));
                            connection.driver = driver;
                        }
                        return;
                    }
                    catch (MySqlException ex)
                    {
                        connection.driver  = null;
                        server.IsAvailable = false;
                        MySqlTrace.LogError(ex.Number, ex.ToString());
                        if (ex.Number == 1042)
                        {
                            // retry to open a failed connection and update its status
                            group.HandleFailover(server, ex);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            } while (true);
        }
        public static ReplicationServerGroup AddGroup(string name, string groupType)
        {
            if (groupType == null)
            {
                groupType = "MySql.Data.MySqlClient.Replication.ReplicationRoundRobinServerGroup";
            }
            Type t = Type.GetType(groupType);
            ReplicationServerGroup g = (ReplicationServerGroup)Activator.CreateInstance(t, name) as ReplicationServerGroup;

            groups.Add(g);
            return(g);
        }
        /// <summary>
        /// Adds a Server Group to the list
        /// </summary>
        /// <param name="name">Group name</param>
        /// <param name="groupType">ServerGroup type reference</param>
        /// <param name="retryTime">Time between reconnections for failed servers</param>
        /// <returns>Server Group added</returns>
        internal static ReplicationServerGroup AddGroup(string name, string groupType, int retryTime)
        {
            if (string.IsNullOrEmpty(groupType))
            {
                groupType = "MySql.Data.MySqlClient.Replication.ReplicationRoundRobinServerGroup";
            }
            Type t = Type.GetType(groupType);
            ReplicationServerGroup g = (ReplicationServerGroup)Activator.CreateInstance(t, name, retryTime) as ReplicationServerGroup;

            groups.Add(g);
            return(g);
        }
Exemple #4
0
        //private static Dictionary<string, ReplicationServerSelector> selectors = new Dictionary<string, ReplicationServerSelector>();

        static ReplicationManager()
        {
            Groups = groups;

            //#if !NETSTANDARD1_6
            // load up our selectors
            //if (MySqlConfiguration.Settings == null) return;

            //foreach (var group in MySqlConfiguration.Settings.Replication.ServerGroups)
            //{
            //    ReplicationServerGroup g = AddGroup(group.Name, group.GroupType, group.RetryTime);
            //    foreach (var server in group.Servers)
            //        g.AddServer(server.Name, server.IsMaster, server.ConnectionString);
            //}

            string databaseServerName  = GetStringValue("DatabaseServerName", "mysql");
            var    databaseServerNames = databaseServerName.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList();

            //如果存在多个服务器,则为mysql组复制
            if (databaseServerNames.Count <= 1)
            {
                return;
            }
            //打乱server信息
            List <string> newDatabaseServerNames = new List <string>();
            Random        random     = new Random();
            int           totalCount = databaseServerNames.Count;

            while (newDatabaseServerNames.Count < totalCount)
            {
                int index = random.Next(totalCount - newDatabaseServerNames.Count);
                if (!newDatabaseServerNames.Contains(databaseServerNames[index]))
                {
                    newDatabaseServerNames.Add(databaseServerNames[index]);
                    databaseServerNames.RemoveAt(index);
                }
            }

            string databaseGroupName = GetStringValue("DatabaseGroupName", "MySQLGroupReplication");
            ReplicationServerGroup g = AddGroup(databaseGroupName, "", 60);

            foreach (var serverName in newDatabaseServerNames)
            {
                bool   isMaster         = true;
                string connectionString = GenerateMySqlConnectionString(serverName);
                g.AddServer(serverName, isMaster, connectionString);
            }
            //#endif
        }
 internal static void GetNewConnection(string groupName, bool master, MySqlConnection connection)
 {
     while (true)
     {
         object obj = ReplicationManager.thisLock;
         lock (obj)
         {
             if (ReplicationManager.IsReplicationGroup(groupName))
             {
                 ReplicationServerGroup group  = ReplicationManager.GetGroup(groupName);
                 ReplicationServer      server = group.GetServer(master, connection.Settings);
                 if (server == null)
                 {
                     throw new MySqlException(Resources.Replication_NoAvailableServer);
                 }
                 try
                 {
                     bool flag2 = false;
                     if (connection.driver == null || !connection.driver.IsOpen)
                     {
                         flag2 = true;
                     }
                     else if (!new MySqlConnectionStringBuilder(server.ConnectionString).Equals(connection.driver.Settings))
                     {
                         flag2 = true;
                     }
                     if (flag2)
                     {
                         Driver driver = Driver.Create(new MySqlConnectionStringBuilder(server.ConnectionString));
                         connection.driver = driver;
                     }
                 }
                 catch (MySqlException ex)
                 {
                     connection.driver  = null;
                     server.IsAvailable = false;
                     MySqlTrace.LogError(ex.Number, ex.ToString());
                     if (ex.Number == 1042)
                     {
                         group.HandleFailover(server, ex);
                         continue;
                     }
                     throw;
                 }
             }
         }
         break;
     }
 }
        internal static ReplicationServerGroup AddGroup(string name, string groupType, int retryTime)
        {
            if (string.IsNullOrEmpty(groupType))
            {
                groupType = "MySql.Data.MySqlClient.Replication.ReplicationRoundRobinServerGroup";
            }
            ReplicationServerGroup replicationServerGroup = (ReplicationServerGroup)Activator.CreateInstance(Type.GetType(groupType), new object[]
            {
                name,
                retryTime
            });

            ReplicationManager.groups.Add(replicationServerGroup);
            return(replicationServerGroup);
        }
        /// <summary>
        /// Assigns a new server driver to the connection object
        /// </summary>
        /// <param name="groupName">Group name</param>
        /// <param name="master">True if the server connection to assign must be a master</param>
        /// <param name="connection">MySqlConnection object where the new driver will be assigned</param>
        internal static void GetNewConnection(string groupName, bool master, MySqlConnection connection)
        {
            do
            {
                lock (thisLock)
                {
                    if (!IsReplicationGroup(groupName))
                    {
                        return;
                    }

                    ReplicationServerGroup group  = GetGroup(groupName);
                    ReplicationServer      server = group.GetServer(master);

                    if (server == null)
                    {
                        throw new MySqlException(Properties.Resources.Replication_NoAvailableServer);
                    }

                    Driver driver = Driver.Create(new MySqlConnectionStringBuilder(server.ConnectionString));
                    if (connection.driver == null ||
                        driver.Settings.ConnectionString != connection.driver.Settings.ConnectionString)
                    {
                        connection.Close();
                        connection.hasBeenOpen = false;
                        try
                        {
                            connection.driver = driver;
                            connection.Open();
                            return;
                        }
                        catch (Exception)
                        {
                            connection.driver  = null;
                            server.IsAvailable = false;
                            // retry to open a failed connection and update its status
                            group.HandleFailover(server);
                        }
                    }
                    else
                    {
                        return;
                    }
                }
            } while (true);
        }
 static ReplicationManager()
 {
     ReplicationManager.groups = new List <ReplicationServerGroup>();
     ReplicationManager.Groups = ReplicationManager.groups;
     if (MySqlConfiguration.Settings == null)
     {
         return;
     }
     foreach (ReplicationServerGroupConfigurationElement current in MySqlConfiguration.Settings.Replication.ServerGroups)
     {
         ReplicationServerGroup replicationServerGroup = ReplicationManager.AddGroup(current.Name, current.GroupType, current.RetryTime);
         foreach (ReplicationServerConfigurationElement current2 in current.Servers)
         {
             replicationServerGroup.AddServer(current2.Name, current2.IsMaster, current2.ConnectionString);
         }
     }
 }
        internal static ReplicationServerGroup GetGroup(string groupName)
        {
            ReplicationServerGroup replicationServerGroup = null;

            foreach (ReplicationServerGroup current in ReplicationManager.groups)
            {
                if (string.Compare(current.Name, groupName, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    replicationServerGroup = current;
                    break;
                }
            }
            if (replicationServerGroup == null)
            {
                throw new MySqlException(string.Format(Resources.ReplicationGroupNotFound, groupName));
            }
            return(replicationServerGroup);
        }
Exemple #10
0
        //private static Dictionary<string, ReplicationServerSelector> selectors = new Dictionary<string, ReplicationServerSelector>();

        static ReplicationManager()
        {
            Groups = groups;

            // load up our selectors
            if (MySqlConfiguration.Settings == null)
            {
                return;
            }

            foreach (var group in MySqlConfiguration.Settings.Replication.ServerGroups)
            {
                ReplicationServerGroup g = AddGroup(group.Name, group.GroupType, group.RetryTime);
                foreach (var server in group.Servers)
                {
                    g.AddServer(server.Name, server.IsSource, server.ConnectionString);
                }
            }
        }
        /// <summary>
        /// Gets a Server Group by name
        /// </summary>
        /// <param name="groupName">Group name</param>
        /// <returns>Server Group if found, otherwise throws an MySqlException</returns>
        internal static ReplicationServerGroup GetGroup(string groupName)
        {
            ReplicationServerGroup group = null;

            foreach (ReplicationServerGroup g in groups)
            {
                if (String.Compare(g.Name, groupName, StringComparison.OrdinalIgnoreCase) != 0)
                {
                    continue;
                }
                group = g;
                break;
            }
            if (group == null)
            {
                throw new MySqlException(String.Format(Resources.ReplicationGroupNotFound, groupName));
            }
            return(group);
        }
        //private static Dictionary<string, ReplicationServerSelector> selectors = new Dictionary<string, ReplicationServerSelector>();

        static ReplicationManager()
        {
            Groups = groups;

#if !CF && !RT
            // load up our selectors
            if (MySqlConfiguration.Settings == null)
            {
                return;
            }

            foreach (var group in MySqlConfiguration.Settings.Replication.ServerGroups)
            {
                ReplicationServerGroup g = AddGroup(group.Name, group.GroupType);
                foreach (var server in group.Servers)
                {
                    g.AddServer(server.Name, server.IsMaster, server.ConnectionString);
                }
            }
#endif
        }
        public static ReplicationServer GetServer(string groupName, bool isMaster)
        {
            ReplicationServerGroup group = ReplicationManager.GetGroup(groupName);

            return(group.GetServer(isMaster));
        }
        /// <summary>
        /// Gets the next server from a replication group
        /// </summary>
        /// <param name="groupName">Group name</param>
        /// <param name="isMaster">True if the server to return must be a master</param>
        /// <returns>Replication Server defined by the Load Balancing plugin</returns>
        internal static ReplicationServer GetServer(string groupName, bool isMaster)
        {
            ReplicationServerGroup group = GetGroup(groupName);

            return(group.GetServer(isMaster));
        }
Exemple #15
0
        /// <summary>
        /// Assigns a new server driver to the connection object
        /// </summary>
        /// <param name="groupName">Group name</param>
        /// <param name="master">True if the server connection to assign must be a master</param>
        /// <param name="connection">MySqlConnection object where the new driver will be assigned</param>
        public static void GetNewConnection(string groupName, bool master, MySqlConnection connection)
        {
            do
            {
                if (!IsReplicationGroup(groupName))
                {
                    return;
                }

                ReplicationServerGroup group  = GetGroup(groupName);
                ReplicationServer      server = group.GetServer(master);

                if (server == null)
                {
                    throw new MySqlException(Properties.Resources.Replication_NoAvailableServer);
                }

                Driver driver = Driver.Create(new MySqlConnectionStringBuilder(server.ConnectionString));
                if (connection.driver == null ||
                    driver.Settings.ConnectionString != connection.driver.Settings.ConnectionString)
                {
                    connection.Close();
                    connection.hasBeenOpen = false;
                    try
                    {
                        connection.driver = driver;
                        connection.Open();
                        return;
                    }
                    catch (Exception)
                    {
                        // retry to open a failed connection and update its status
                        connection.driver  = null;
                        server.IsAvailable = false;

                        BackgroundWorker worker = new BackgroundWorker();
                        worker.DoWork += delegate(object sender, DoWorkEventArgs e)
                        {
                            bool isRunning            = false;
                            ReplicationServer server1 = e.Argument as ReplicationServer;
                            int retryTime             = ReplicationManager.GetGroup(groupName).RetryTime;
#if !RT
                            System.Timers.Timer timer = new System.Timers.Timer(retryTime * 1000.0);


                            System.Timers.ElapsedEventHandler elapsedEvent = delegate(object sender1, System.Timers.ElapsedEventArgs e1)
                            {
                                if (isRunning)
                                {
                                    return;
                                }
                                try
                                {
                                    isRunning = true;
                                    using (MySqlConnection connectionFailed = new MySqlConnection(server.ConnectionString))
                                    {
                                        connectionFailed.Open();
                                        server1.IsAvailable = true;
                                        timer.Stop();
                                    }
                                }
                                catch
                                {
                                    MySqlTrace.LogWarning(0,
                                                          string.Format(Properties.Resources.Replication_ConnectionAttemptFailed, server1.Name));
                                }
                                finally
                                {
                                    isRunning = false;
                                }
                            };
                            timer.Elapsed += elapsedEvent;
                            timer.Start();
                            elapsedEvent(sender, null);
#else
                            Windows.UI.Xaml.DispatcherTimer timer = new Windows.UI.Xaml.DispatcherTimer();
                            TimeSpan ts = new TimeSpan(retryTime * 1000);
                            System.EventHandler <object> elapsedEvent = (TickSender, TickEventArgs) =>
                            {
                                if (isRunning)
                                {
                                    return;
                                }
                                try
                                {
                                    isRunning = true;
                                    using (MySqlConnection connectionFailed = new MySqlConnection(server.ConnectionString))
                                    {
                                        connectionFailed.Open();
                                        server1.IsAvailable = true;
                                        timer.Stop();
                                    }
                                }
                                catch
                                {
                                    MySqlTrace.LogWarning(0,
                                                          string.Format(Properties.Resources.Replication_ConnectionAttemptFailed, server1.Name));
                                }
                                finally
                                {
                                    isRunning = false;
                                }
                            };
                            timer.Tick += elapsedEvent;
                            elapsedEvent(sender, null);
                            timer.Start();
#endif
                        };

                        worker.RunWorkerAsync(server);
                    }
                }
                else
                {
                    return;
                }
            } while (true);
        }
        public static void GetNewConnection(string groupName, bool master, MySqlConnection connection)
        {
            while (true)
            {
                if (!ReplicationManager.IsReplicationGroup(groupName))
                {
                    break;
                }
                ReplicationServerGroup group  = ReplicationManager.GetGroup(groupName);
                ReplicationServer      server = group.GetServer(master);
                if (server == null)
                {
                    goto Block_2;
                }
                Driver driver = Driver.Create(new MySqlConnectionStringBuilder(server.ConnectionString));
                if (connection.driver == null || driver.Settings.ConnectionString != connection.driver.Settings.ConnectionString)
                {
                    connection.Close();
                    connection.hasBeenOpen = false;
                    try
                    {
                        connection.driver = driver;
                        connection.Open();
                    }
                    catch (Exception)
                    {
                        connection.driver  = null;
                        server.IsAvailable = false;
                        BackgroundWorker backgroundWorker = new BackgroundWorker();
                        backgroundWorker.DoWork += delegate(object sender, DoWorkEventArgs e)
                        {
                            bool isRunning            = false;
                            ReplicationServer server1 = e.Argument as ReplicationServer;
                            int   retryTime           = ReplicationManager.GetGroup(groupName).RetryTime;
                            Timer timer = new Timer((double)retryTime * 1000.0);
                            ElapsedEventHandler elapsedEventHandler = delegate(object sender1, ElapsedEventArgs e1)
                            {
                                if (isRunning)
                                {
                                    return;
                                }
                                try
                                {
                                    isRunning = true;
                                    using (MySqlConnection mySqlConnection = new MySqlConnection(server.ConnectionString))
                                    {
                                        mySqlConnection.Open();
                                        server1.IsAvailable = true;
                                        timer.Stop();
                                    }
                                }
                                catch
                                {
                                    MySqlTrace.LogWarning(0, string.Format(Resources.Replication_ConnectionAttemptFailed, server1.Name));
                                }
                                finally
                                {
                                    isRunning = false;
                                }
                            };
                            timer.Elapsed += elapsedEventHandler;
                            timer.Start();
                            elapsedEventHandler(sender, null);
                        };
                        backgroundWorker.RunWorkerAsync(server);
                        continue;
                    }
                    return;
                }
                return;
            }
            return;

Block_2:
            throw new MySqlException(Resources.Replication_NoAvailableServer);
        }
Exemple #17
0
        /// <summary>
        /// Assigns a new server driver to the connection object
        /// </summary>
        /// <param name="groupName">Group name</param>
        /// <param name="master">True if the server connection to assign must be a master</param>
        /// <param name="connection">MySqlConnection object where the new driver will be assigned</param>
        internal static void GetNewConnection(string groupName, bool master, MySqlConnection connection)
        {
            do
            {
                lock (thisLock)
                {
                    if (!IsReplicationGroup(groupName))
                    {
                        return;
                    }

                    ReplicationServerGroup group  = GetGroup(groupName);
                    ReplicationServer      server = group.GetServer(master, connection.Settings);

                    if (server == null)
                    {
                        throw new MySqlException(Resources.Replication_NoAvailableServer);
                    }

                    //根据主连接字符串配置的账号、密码、数据库、端口,使用新的server的连接字符串(不更新,每次都添加)
                    string newServerConnectionString = $"{server.ConnectionString}uid={connection.Settings.UserID};pwd={connection.Settings.Password};Database={connection.Settings.Database};port={connection.Settings.Port};";

                    try
                    {
                        bool isNewServer = false;
                        if (connection.driver == null || !connection.driver.IsOpen)
                        {
                            isNewServer = true;
                        }
                        else
                        {
                            MySqlConnectionStringBuilder msb = new MySqlConnectionStringBuilder(newServerConnectionString);
                            if (!msb.Equals(connection.driver.Settings))
                            {
                                isNewServer = true;
                            }
                        }
                        if (isNewServer)
                        {
                            var       builder = new MySqlConnectionStringBuilder(newServerConnectionString);
                            MySqlPool pool    = MySqlPoolManager.GetPool(builder);
                            Driver    driver  = pool.GetConnection();
                            //Driver driver = Driver.Create(new MySqlConnectionStringBuilder(newServerConnectionString));
                            connection.driver = driver;
                        }
                        return;
                    }
                    catch (MySqlException ex)
                    {
                        connection.driver = null;
                        MySqlTrace.LogError(ex.Number, ex.ToString());
                        if (ex.Number == 1042)
                        {
                            //只有连不上的时候才标记为不可用
                            server.IsAvailable = false;
                            //连接失败时打印日志(故障情况)
                            Console.WriteLine("GetNewConnection Before HandleFailover >> Error:{0},{1}Number={2},ConnectionString={3}", ex.Message, ex.InnerException == null ? "" : "InnerException:" + ex.InnerException.Message + ",", ex.Number, newServerConnectionString);
                            server.ConnectionString = newServerConnectionString;
                            // retry to open a failed connection and update its status
                            group.HandleFailover(server, ex);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            } while (true);
        }