生產環境已部署 MSMQ WCF 服務,需新增 WCF 客戶端調用,要求**不重啟服務器**、通過配置文件完成。
將 WCF 服務寄宿於 Windows Service / Console App / WPF App 中,而非 IIS/WAS。
優勢:進程完全可控,配置文件 (app.config) 修改後可通過 ServiceHost 重新載入或動態添加端點。
// 動態添加端點示例
var host = new ServiceHost(typeof(MyMsmqService));
var binding = new NetMsmqBinding();
host.AddServiceEndpoint(typeof(IMyContract), binding, "net.msmq://localhost/private/newqueue");
host.Open();
// 配置文件變更監聽
FileSystemWatcher watcher = new FileSystemWatcher(AppDomain.CurrentDomain.BaseDirectory, "app.config");
watcher.Changed += (s, e) => {
// 重新讀取配置並重建端點(需關閉舊 host 開啟新 host)
host.Close();
host = new ServiceHost(typeof(MyMsmqService));
host.Open();
};
watcher.EnableRaisingEvents = true;
web.config 觸發應用程序域回收,WCF 服務自動重新載入配置。web.config 即可,IIS 會優雅回收(現有連接完成後新請求走新配置)。<system.serviceModel>
<bindings>
<netMsmqBinding>
<binding name="msmqBinding" />
</netMsmqBinding>
</bindings>
<services>
<service name="MyService">
<endpoint address="net.msmq://localhost/private/queue1" binding="netMsmqBinding" bindingConfiguration="msmqBinding" contract="IContract" />
<!-- 新增端點只需在這裡添加 -->
<endpoint address="net.msmq://localhost/private/queue2" binding="netMsmqBinding" bindingConfiguration="msmqBinding" contract="IContract" />
</service>
</services>
</system.serviceModel>
保存 web.config/app.config 後,WCF 運行時自動偵測變更並應用新端點(需 serviceAutoStartEnabled="true")。
MessageQueue.Create(@".\private$\newqueue"))。ReceiveMessage/PeekMessage 權限。NetMsmqBinding 設置 ExactlyOnce=true、Durable=true。Self-Host 提供最大靈活性**,適合頻繁動態調整;**IIS + 配置文件熱加載** 適合標準部署流程。兩者均可實現「不重啟服務器(作業系統層面)」,僅回收應用程序域/進程。