首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

.NET WCF 簡化之道:內部通訊服務工廠 (ICSFactory) 統一服務位置透明化

     編輯:關於.NET

前言

WCF 功能強大但配置繁瑣:散落的 config 檔、客戶端需知服務位址、部署維護困難。本文提出 Internal Communication Service (ICS) 架構,透過 ICSFactory 統一服務建立、ServiceLocator 集中位址管理,實現 WCF 服務位置透明化。

簡化後的客戶端呼叫方式

非交易呼叫


IUser userSrv = ICSFactory.Create();
var result = userSrv.GetUserName("1", "2", "3");
ICSFactory.Close(userSrv);

交易範圍呼叫 (分散式交易)


string result = string.Empty;
using (TransactionScope ts = new TransactionScope())
{
    IUser userSrv = ICSFactory.Create();
    IAdmin adminSrv = ICSFactory.Create();
    
    result = userSrv.GetUserName("1", "2", "3");
    result = adminSrv.CheckPermission(100).ToString();
    
    ts.Complete();
    ICSFactory.Close(userSrv);
    ICSFactory.Close(adminSrv);
}

服務位址集中管理:a2d.service.config

appSetting 指定路徑:\\fs\root\a2d.service.config

<?xml version="1.0" encoding="utf-8"?>
<A2D>
    <ServiceLocator>
        <Service ContractNamespace="DEsbInterface" Contract="IUser">
            <Url EndpointType="Tcp">net.tcp://192.168.1.100:9999/usersrv</Url>
        </Service>
        <Service ContractNamespace="DEsbInterface" Contract="IAdmin">
            <Url EndpointType="Tcp">net.tcp://192.168.1.100:9998/adminsrv</Url>
        </Service>
    </ServiceLocator>
</A2D>

適用場景:多客戶端節點統一管理

4 台 Server 作為 WCF 客戶端

  • 4 台 Server 同時呼叫 WCF 服務
  • 服務遷移/擴展時,僅更新中央設定檔
  • 所有客戶端零配置變更、零重新部署

ICSFactory 核心實作


public class ICSFactory
{
    public static T Create()
    {
        string contractNamespace = typeof(T).Namespace;
        string contract = typeof(T).Name;
        
        // 1. 從 ServiceLocator 取得位址資訊
        Location location = ServiceLocator.Locate(contractNamespace, contract);
        
        // 2. 程式碼建立 Binding
        NetTcpBinding binding = new NetTcpBinding();
        binding.ReceiveTimeout = new TimeSpan(0, 10, 0);
        binding.Security.Mode = SecurityMode.None;
        binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
        
        // 3. 交易流程支援
        binding.TransactionFlow = true;
        binding.TransactionProtocol = TransactionProtocol.OleTransactions;
        
        // 4. 建立通道
        EndpointAddress address = new EndpointAddress(location.Url);
        T proxy = ChannelFactory.CreateChannel(binding, address);
        
        return proxy;
    }

    public static void Close(object proxy)
    {
        if (proxy == null) return;
        IDisposable disposable = proxy as IDisposable;
        if (disposable != null) disposable.Dispose();
    }
}

ServiceLocator 實作


public static class ServiceLocator
{
    private static Dictionary serviceCache = new Dictionary();
    
    // 啟動時載入 XML 到記憶體 (Service、Url 物件)
    
    public static Location Locate(string contractNamespace, string contract)
    {
        string key = string.Format("{0}.{1}", contractNamespace, contract);
        Service srv;
        
        if (!serviceCache.ContainsKey(key))
        {
            srv = FindService(contractNamespace, contract);
            serviceCache[key] = srv;
        }
        else srv = serviceCache[key];
        
        if (srv.Urls == null || srv.Urls.Count == 0)
            throw new Exception(string.Format("Service url not found [{0}.{1}]", contractNamespace, contract));
        
        Url url = srv.Urls.First(); // 可擴展負載平衡邏輯
        return new Location { EndpointType = url.EndpointType, Url = url.ReferenceUrl };
    }
    
    private static Service FindService(string contractNamespace, string contract, Service srv = null)
    {
        var matched = LocatorServiceConfiguration.Services
            .Where(t => t.Contract == contract && t.ContractNamespace == contractNamespace)
            .ToList();
        
        if (matched == null || matched.Count == 0)
            throw new Exception(string.Format("Service not found [{0}.{1}]", contractNamespace, contract));
        
        return matched.First();
    }
}

架構優勢總結

傳統 WCFICS 架構
每客戶端獨立 config中央化單一設定檔
服務位址硬編碼/分散ServiceLocator 動態解析
部署需同步更新所有客戶端僅更新中央設定,客戶端零感知
Binding 參數分散在 config程式碼集中管理、版本控制
交易流程配置複雜Binding 統一啟用 TransactionFlow

擴展方向

  • 負載平衡:Url 清單支援多端點,Locate 實作輪詢/隨機/加權策略
  • 熔斷器:整合 Polly/Hystrix 實作失敗快速返回
  • 服務發現:對接 Consul/Etcd/Zookeeper 取代靜態 XML
  • 多協定支援:HTTP/HTTPS/NamedPipe 依 EndpointType 動態建立 Binding
  • 驗證授權:中央管理 ClientCredentialType、Certificate、Token

查看本欄目

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved