与Burlap和Hessian相反,这些都是轻量级协议,使用其自带的灵活的序列化机制,Spring HTTP调用者使用标准的Java序列化机制通过HTTP暴露业务接口。如果你的参数和返回的类型很复杂,其不能通过Burlap和Hessian序列化,这是一个很大的优点(当选择一个远程技术的时候在下一章要考虑更多的细节)。
在高级选项中,Spring要不使用由JDK提供的标准机制,要不使用Apache的 HttpComponents
执行HTTP调用。如果你需要使用更强大和容易使用的功能,就使用后者。
21.4.1 暴露业务对象
为一个对象设置HTTP调用者机制,与使用Hessian或Burlap非常相似。就比如Hessian支持提供的HessianServiceExporter
,Spring的HttpInvoker支持提供了org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter
.
为暴露一个Spring Web MVC DispatcherServlet
内的AccountService
(上述提到的),下面的配置需要在分发的应用上下文中替换。
<bean name="/AccountService" class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
<property name="service" ref="accountService"/>
<property name="serviceInterface" value="example.AccountService"/>
</bean>
这样的输出定义将通过
DispatcherServlet
的标准映射机制暴露,如同上述Hessian或Burlap解释的那样。
作为可选地,在你的根应用程序上下文中创建一个HttpInvokerServiceExporter
(例如:在'WEB-INF/applicationContext.xml'
中)
<bean name="accountExporter" class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
<property name="service" ref="accountService"/>
<property name="serviceInterface" value="example.AccountService"/>
</bean>
另外,在web.xml中为这个输出定义一个对应的Servlet,其Servlet名字与目标输出者的bean名匹配。
<servlet>
<servlet-name>accountExporter</servlet-name>
<servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>accountExporter</servlet-name>
<url-pattern>/remoting/AccountService</url-pattern>
</servlet-mapping>
如果在一个Servlet容器外部运行并且使用oracle的Java 6 版本,那么你可以使用内建的HTTP服务实现。你可以一起配置
SimpleHttpServerFactoryBean
,如下面例子所示:
<bean name="accountExporter"
class="org.springframework.remoting.httpinvoker.SimpleHttpInvokerServiceExporter">
<property name="service" ref="accountService"/>
<property name="serviceInterface" value="example.AccountService"/>
</bean>
<bean id="httpServer"
class="org.springframework.remoting.support.SimpleHttpServerFactoryBean">
<property name="contexts">
<util:map>
<entry key="/remoting/AccountService" value-ref="accountExporter"/>
</util:map>
</property>
<property name="port" value="8080" />
</bean>
21.4.2 在客户端联系业务
在客户端联系业务也与Hessian和Burlap是非常相似的。使用一个代理,Spring可以将你的调用转换为HTTP POST请求道URL,其指向暴露的业务。
<bean id="httpInvokerProxy" class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
<property name="serviceUrl" value="http://remotehost:8080/remoting/AccountService"/>
<property name="serviceInterface" value="example.AccountService"/>
</bean>
如同之前提到的,你可以选择你想使用的客户端。默认地,
HttpInvokerProxy
使用了JDK的HTTP功能,但是了你也可以使用Apache的
HttpComponents
客户端来设置
httpInvokerRequestExecutor
属性
property name="httpInvokerRequestExecutor">
<bean class="org.springframework.remoting.httpinvoker.HttpComponentsHttpInvokerRequestExecutor"/>
</property>