模組化架構中,跨進程、跨機器的服務互調是核心挑戰。本文展示基於 .NET Remoting 的 OSGi 原型,實現多模組分散式部署、服務註冊發現、跨 AppDomain 透明呼叫。

tcp://localhost:8888/OSGI)OpenService 命令,讓目標 OSGi 註冊 TCP ChannelAppDomain.DoCallBack 連接至目標 OSGi 新開的服務端點<?xml version="1.0" encoding="utf-8"?>
<Manifests>
<ServicePort>1000</ServicePort>
<RemoteServiceMap>
<Service TargetIP="127.0.0.1" TargetPort="2000">
OrderModule.PublicInterfaces.IOrderProcessor
</Service>
</RemoteServiceMap>
</Manifests>
<?xml version="1.0" encoding="utf-8"?>
<Manifests>
<ServicePort>2000</ServicePort>
<Manifest>D:\Projects\OSGIDemo\OrderModule\bin\Debug\Manifest.xml</Manifest>
<RemoteServiceMap>
<Service TargetIP="127.0.0.1" TargetPort="3000">
LoggingModule.PublicInterfaces.ILog
</Service>
</RemoteServiceMap>
</Manifests>
<?xml version="1.0" encoding="utf-8"?>
<Module>
<Name>Order Module</Name>
<Version>1</Version>
<Assembly>OrderModule</Assembly>
<Activator>OrderModule.Activator</Activator>
<RequiredService>LoggingModule.PublicInterfaces.ILog</RequiredService>
<ProvidedService>OrderModule.PublicInterfaces.IOrderProcessor</ProvidedService>
</Module>
using OSGIFramework;
public class Activator : BundleActivator
{
public override void Startup(BundleContext bc)
{
Console.WriteLine("OrderModule Startup");
BundleContext.Current.RegisterProvidedService();
}
public override void Stop(BundleContext bc)
{
Console.WriteLine("OrderModule Stop");
BundleContext.Current.UnRegisterProvidedService();
}
}
public class OrderProcessorImpl : ServiceProvider, IOrderProcessor
{
public Guid PlaceOrder(OrderDto order)
{
BundleContext ctx = BundleContext.Current;
ILog log = ctx.GetProvidedService(); // 透明取得遠端服務
log.Log("log something...");
Console.WriteLine("PlaceOrder body");
return Guid.NewGuid();
}
}
關鍵點:繼承 ServiceProvider (必須繼承 MarshalByRefObject) 才能跨 AppDomain 封送。
static void Main(string[] args)
{
BundleRuntime runtime = new BundleRuntime();
runtime.Start();
BundleContext ctx = BundleContext.Current;
IOrderProcessor processor = (IOrderProcessor)ctx.GetProvidedService(typeof(IOrderProcessor).FullName);
OrderDto order = new OrderDto();
Guid id = processor.PlaceOrder(order);
Console.WriteLine("id=" + id.ToString());
Console.ReadKey();
runtime.Stop();
runtime.Dispose();
}


程式碼下載:OSGIDemo2.rar