Example #1
0
        static void Main(string[] args)
        {
            LoadBalance balancer = LoadBalance.GetLoadBalance();

            balancer.AddServer(new Server("服务器1", "192.168.1.1"));
            balancer.AddServer(new Server("服务器2", "192.168.1.2"));
            balancer.AddServer(new Server("服务器3", "192.168.1.3"));
            balancer.AddServer(new Server("服务器4", "192.168.1.4"));
            balancer.AddServer(new Server("服务器5", "192.168.1.5"));
            balancer.AddServer(new Server("服务器6", "192.168.1.6"));

            //模拟客户端请求的分发
            for (int i = 0; i < 10; i++)
            {
                Server server = balancer.GetServer();
                Console.WriteLine("请求的服务器名称是:{0},服务器的id是:{1}", server.Name, server.Ip);
            }
            Console.Read();
        }
Example #2
0
        /// <summary>
        /// 用共有静态保证整个程序中,该LoadBalance只能实例化一次
        /// </summary>
        /// <returns></returns>
        public static LoadBalance GetLoadBalance()
        {

            //判断实例是否存在,不存在再加锁处理
            if (instance == null)
            {
                //加锁的程序在某一刻只允许一个线程访问
                lock (isLock)
                {
                    //第二重判断
                    if (instance == null)
                    {
                        instance = new LoadBalance();   //创建实例
                    }
                }
                instance = new LoadBalance();
            }
            return instance;

        }