單一應用程式集區承載過多站點會導致資源爭用、回收影響範圍過大、故障隔離困難。需開發自動化工具,依規則將站點均勻分散至多個集區,支援:
AppPool #N、aspnet1-N 等)參考組件:C:\Windows\System32\inetsrv\Microsoft.Web.Administration.dll
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Web.Administration;
namespace IisPoolBalancer
{
public class PoolBalancer
{
private readonly ServerManager _server = new ServerManager();
///
/// 執行平衡
///
/// 每集區最大站點數
/// 指定集區名稱,null 表示全域
public void Balance(int maxSitesPerPool, string targetPoolName = null)
{
var pools = targetPoolName == null
? _server.ApplicationPools.Where(p => !IsSystemPool(p.Name)).ToList()
: _server.ApplicationPools.Where(p => p.Name == targetPoolName).ToList();
foreach (var pool in pools)
{
var sites = GetSitesInPool(pool.Name).ToList();
if (sites.Count <= maxSitesPerPool) continue;
Console.WriteLine($"[{pool.Name}] 站點數 {sites.Count} > 上限 {maxSitesPerPool},開始分流...");
// 依名稱排序,保留前 N 個,其餘遷移
var toMove = sites.Skip(maxSitesPerPool).ToList();
foreach (var site in toMove)
{
if (site.Name == pool.Name) continue; // 同名跳過
string newPool = GetOrCreateTargetPool(pool.Name, site.Name);
MoveSiteToPool(site.Name, newPool);
Console.WriteLine($" 遷移站點 [{site.Name}] -> [{newPool}]");
}
}
}
private IEnumerable GetSitesInPool(string poolName)
{
return _server.Sites.Where(s => s.Applications["/"].ApplicationPoolName == poolName);
}
private bool IsSystemPool(string name) =>
name.Equals("DefaultAppPool", StringComparison.OrdinalIgnoreCase) ||
name.StartsWith("AppPool #", StringComparison.OrdinalIgnoreCase);
private string GetOrCreateTargetPool(string sourcePool, string siteName)
{
// 規則 1: DefaultAppPool 或 AppPool #* -> 建立/使用 AppPool #N
if (sourcePool.Equals("DefaultAppPool", StringComparison.OrdinalIgnoreCase) ||
sourcePool.StartsWith("AppPool #", StringComparison.OrdinalIgnoreCase))
{
int idx = 1;
while (_server.ApplicationPools.Any(p => p.Name == $"AppPool #{idx}")) idx++;
string newName = $"AppPool #{idx}";
CreatePoolIfNotExists(newName);
return newName;
}
// 規則 2: aspnet1/2/3/4 -> aspnetX-N
if (sourcePool.StartsWith("aspnet", StringComparison.OrdinalIgnoreCase))
{
int idx = 1;
while (_server.ApplicationPools.Any(p => p.Name == $"{sourcePool}-{idx}")) idx++;
string newName = $"{sourcePool}-{idx}";
CreatePoolIfNotExists(newName);
return newName;
}
// 其它: 來源集區名 + -N
int fallbackIdx = 1;
while (_server.ApplicationPools.Any(p => p.Name == $"{sourcePool}-{fallbackIdx}")) fallbackIdx++;
string fallback = $"{sourcePool}-{fallbackIdx}";
CreatePoolIfNotExists(fallback);
return fallback;
}
private void CreatePoolIfNotExists(string name)
{
if (_server.ApplicationPools.Any(p => p.Name == name)) return;
var pool = _server.ApplicationPools.Add(name);
pool.ManagedRuntimeVersion = "v4.0";
pool.ManagedPipelineMode = ManagedPipelineMode.Integrated;
_server.CommitChanges();
}
private void MoveSiteToPool(string siteName, string targetPool)
{
var site = _server.Sites[siteName];
if (site == null) return;
site.Applications["/"].ApplicationPoolName = targetPool;
_server.CommitChanges();
}
}
}
class Program
{
static void Main(string[] args)
{
// 參數解析: "50" 或 "50 aspnet1"
int maxSites = 50;
string targetPool = null;
if (args.Length > 0)
{
string[] parts = args[0].Split(' ', StringSplitOptions.RemoveEmptyEntries);
maxSites = int.Parse(parts[0]);
if (parts.Length > 1) targetPool = parts[1];
}
var balancer = new PoolBalancer();
try
{
balancer.Balance(maxSites, targetPool);
Console.WriteLine("平衡完成。");
}
catch (Exception ex)
{
Console.Error.WriteLine($"錯誤: {ex.Message}");
}
finally
{
balancer.Dispose();
}
}
}
| 項目 | 說明 |
|---|---|
| 權限 | 需以 Administrator 執行,或啟用 IIS 管理權限 |
| 參考組件 | 專案加入 Microsoft.Web.Administration 參考 (Copy Local = False) |
| 目標框架 | .NET Framework 4.7.2+ / .NET Core 3.1+ (需 NuGet Microsoft.Web.Administration) |
| 備份 | 執行前備份 %windir%\system32\inetsrv\config\applicationHost.config |
| 排程 | 可做成 Windows Service / 排程工作 定期執行 |
System.Diagnostics.PerformanceCounter 讀取各集區工作進程資源使用量,依負載而非單純站點數分流。--dry-run 僅輸出計畫不實際變更。