Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Spring + RMI + Hibernate 發布多個遠端服務的實作思路

用 Spring 的 RMI 支援發布遠端服務時,若只有一個介面倒還簡單;一旦要同時對外提供兩組、甚至更多組服務,配置就要講究一點。基本原則是:一個服務對應一個 RmiServiceExporter,客戶端 likewise 一個服務對應一個 RmiProxyFactoryBean。

服務端:兩個 Exporter 共用同一個註冊埠

<!-- RMI service 01 -->
<bean id="logPersonService"
      class="org.springframework.remoting.rmi.RmiServiceExporter">
  <!-- RmiServiceExporter 對服務名沒有特殊要求 -->
  <property name="serviceName"><value>LogPerson</value></property>
  <property name="service"><ref bean="PersonTarget"/></property>
  <property name="serviceInterface"><value>com.hibernate.ILogPerson</value></property>
  <!-- 避免與默認的 RMI 註冊埠衝突,因此修改為 1200 -->
  <property name="registryPort"><value>1200</value></property>
</bean>

<!-- RMI service 02 -->
<bean id="BayService"
      class="org.springframework.remoting.rmi.RmiServiceExporter">
  <property name="serviceName"><value>Bay</value></property>
  <property name="service"><ref bean="BayTarget"/></property>
  <property name="serviceInterface"><value>com.hibernate.IBay</value></property>
  <property name="registryPort"><value>1200</value></property>
</bean>

註冊埠可以相同,靠 serviceName 區分;如果讓兩個 exporter 各自佔用不同埠,客戶端 URL 也要跟著改,反而更麻煩。

客戶端:兩個 Proxy 工廠

<!-- RMI Client 01 -->
<bean id="LogPerson"
      class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
  <property name="serviceUrl"><value>rmi://192.168.25.10:1200/LogPerson</value></property>
  <property name="serviceInterface"><value>com.hibernate.ILogPerson</value></property>
</bean>

<!-- RMI Client 02 -->
<bean id="Bay"
      class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
  <property name="serviceUrl"><value>rmi://192.168.25.10:1200/Bay</value></property>
  <property name="serviceInterface"><value>com.hibernate.IBay</value></property>
</bean>

主程式取得服務

// 獲得 RMI 服務
ILogPerson clientLog = (ILogPerson) cfactory.getBean("LogPerson");
IBay clientBay = (IBay) cfactory.getBean("Bay");

不同服務用不同的 getBean 名稱即可,程式碼層面完全不需要感知背後是遠端呼叫。

做關聯物件時報的錯

Exception in thread "main" org.springframework.remoting.RemoteAccessException:
Could not access remote service [rmi://192.168.25.10:1199/BankService];
  nested exception is java.rmi.MarshalException: error marshalling arguments;
  nested exception is: java.io.NotSerializableException: springexample.hibernate.Account

  at springexample.hibernate.TestClient.main(TestClient.java:40)
Caused by: java.rmi.MarshalException: error marshalling arguments; nested exception is:
Caused by: java.io.NotSerializableException: springexample.hibernate.Account

一開始容易被 marshalling arguments 這個字搞糊塗,其實意思很直白:RMI 在傳參數時必須把物件序列化,而你傳過去的實體類沒有實作 Serializable。解法就是讓 Account 這類跨網段傳遞的實體類繼承 java.io.Serializable,並補上 serialVersionUID,問題立刻消失。

順帶一提,Hibernate 的關聯物件若使用懶加載,還可能在序列化時觸發 LazyInitializationException,那時需要在服務端先把需要的欄位取出來,再交給 RMI 傳輸。

Copyright © Linux教程網 All Rights Reserved