Http Invoker


Http Invoker使用HTTP傳送物件,傳送時使用Java的序列化機制來傳送,由於透過HTTP傳送,所以在使用它們時要搭配Spring Web框架來使用,也就是使用到DispatcherServlet,可以改寫 Hessian、Burlap,只要修改一下service-config.xml就可以了:
  • service-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<bean id="urlMapping"
class="org.springframework.web.servlet.
→ handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/some.service">serviceExporter</prop>
</props>
</property>
</bean>

<bean id="viewResolver"
class="org.springframework.web.servlet.
→ view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>

<bean id="someService"
class="onlyfun.caterpillar.SomeServiceImpl"/>

<bean id="serviceExporter"
class="org.springframework.remoting.
→ httpinvoker.HttpInvokerServiceExporter">
<property name="service">
<ref bean="someService"/>
</property>
<property name="serviceInterface">
<value>onlyfun.caterpillar.ISomeService</value>
</property>
</bean>
</beans>

接下來客戶端的部份,可以改寫 Hessian、Burlap 的內容,修改一下Bean定義檔的內容:
  • invoker-client.xml
<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<bean id="someServiceProxy"
class="org.springframework.remoting.
→ httpinvoker.HttpInvokerProxyFactoryBean">
<property name="serviceUrl">
<value>
http://localhost:8080/HttpInvokerDemo/some.service
</value>
</property>
<property name="serviceInterface">
<value>onlyfun.caterpillar.ISomeService</value>
</property>
</bean>
</beans>

注意到"serviceUrl"屬性的設定,它是個標準的HTTP請求位址,來撰寫個簡單的客戶端程式以使用Http Invoker伺服器上的服務:
  • HessianClient.java
package onlyfun.caterpillar;

import org.springframework.context.ApplicationContext;
import org.springframework.context.
support.FileSystemXmlApplicationContext;

public class HessianClient {
public static void main(String[] args) {
ApplicationContext context =
new FileSystemXmlApplicationContext(
"invoker-client.xml");

ISomeService service =
(ISomeService) context.getBean("someServiceProxy");

String result1 = service.doSomeService("Some request");
System.out.println(result1);

int result2 = service.doOtherService(1);
System.out.println(result2);
}
}

執行的結果與 RMI 是相同的。