Spring Framework中有对RMI,Hessian,Burlap,JAX-RPC,JAX-WS.JMS的服务支持,更方便的用于开发异构的服务系统,自身也有HTTPinvoker技术提供远端服务.
以下示例来自SpringFramework-doc文档, 我们先建立用于测试的实体、服务接口类:public class Account implements Serializable{
private String name;
public String getName(){
return name;
}
public void setName(String name) {
this.name = name;
}
}
public interface AccountService {
public void insertAccount(Account account);
public List<Account> getAccounts(String name);
}
// 服务的具体实现类
public class AccountServiceImpl implements AccountService {
public void insertAccount(Account acc) {
// do something...
}
public List<Account> getAccounts(String name) {
// do something...
}
}
下面我们就用caucho公司的hessian技术来提供一个基于HTTP的服务:
首先需要下载hessian包:http://www.caucho.com.
然后配置web.xml
<servlet>
<servlet-name>remoting</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>remoting</servlet-name>
<url-pattern>/remoting/*</url-pattern>
</servlet-mapping>
建立spring xml 配置remoting-servlet.xml通过Spring包装一个接口为hessian服务:
<bean id="accountService" class="example.AccountServiceImpl">
<!-- any additional properties, maybe a DAO? -->
</bean>
<bean name="/AccountService" class="org.springframework.remoting.caucho.HessianServiceExporter">
<property name="service" ref="accountService"/>
<property name="serviceInterface" value="example.AccountService"/>
</bean>
这样 hessian的服务就通过'http://HOST:8080/remoting/AccountService'.来暴露给客户端调用
在客户端中调用
通过Spring来配置测试BEAN
public class SimpleObject {
private AccountService accountService;
public void setAccountService(AccountService accountService) {
this.accountService = accountService;
}
// additional methods using the accountService
}
<bean class="example.SimpleObject">
<property name="accountService" ref="accountService"/>
</bean>
<bean id="accountService" class="org.springframework.remoting.caucho.HessianProxyFactoryBean">
<property name="serviceUrl" value="http://remotehost:8080/remoting/AccountService"/>
<property name="serviceInterface" value="example.AccountService"/>
</bean>
servicePort属性被省略了(默认为0)。这意味着匿名端口将用于与服务通信。
相关阅读: