Spring远程调用-HttpInvokerProxyFactoryBean和HttpInvokerServiceExporter

Spring 远程调用HttpInvokerServiceExporter和HttpInvokerProxyFactoryBean的使用小计。

Spring 允许通过HTTP协议实现远程调用,提供了HttpInvokerProxyFactoryBeanHttpInvokerServiceExporter。在服务端暴漏远程调用接口,在客户端生成一个代理对象,通过代理对象调用远程接口,使用方式比较简单直接。

服务端

  1. 定义远程接口和实现

    1
    2
    3
    4
    5
    6
    7
    public interface AppService {
    /// method
    }
    public class AppServiceImpl implements AppService {
    /// method
    }
  2. 声明HttpInvokerServiceExporter bean

    1
    2
    3
    4
    5
    6
    <bean name="remoteAppService" class="com.frame.rmote.RemoteServiceImpl" />
    <bean name="appService" class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
    <property name="service" ref="remoteAppService" />
    <property name="serviceInterface" value="me.meiqiu.app.AppService" />
    </bean>
  3. 暴漏远程URL

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <bean id="simpleUrlRequestHandler"
    class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="alwaysUseFullPath" value="true" />
    <property name="urlMap">
    <map>
    <!-- 远程调用的输出,注意向外暴露URL的安全性 -->
    <entry key="/remote/app/service" value-ref="appService" />
    </map>
    </property>
    </bean>

客户端

创建HttpInvokerProxyFactoryBean对象(二选1)

a. 代码创建方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* 动态创建HttpInvokerProxyFactoryBean
*
* Created by meiqiu.me on 2017/9/1.
*/
public class HttpInvokerProxyFactory<Client extends Object> {
public Client getProxy(String serviceUrl, Class serviceInterface) {
HttpInvokerProxyFactoryBean factoryBean = new HttpInvokerProxyFactoryBean();
factoryBean.setServiceUrl(serviceUrl);
factoryBean.setServiceInterface(serviceInterface);
factoryBean.afterPropertiesSet();
return factoryBean.getObject();
}
/*public static void main(String[] args) {
String serviceUrl = "http://meiqiu.me:8080/remote/app/service";
AppService client = new HttpInvokerProxyFactory<AppService>().getProxy(md5ClientService, serviceUrl, AppService.class);
}*/
}

b. xml方式:

1
2
3
4
5
<bean id="appServiceProxy"
class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
<property name="serviceUrl" value="${service.url}/remote/app/service" />
<property name="serviceInterface" value="me.meiqiu.app.AppService" />
</bean>

完。