1. 程式人生 > >使用Spring框架實現遠程服務暴露與調用

使用Spring框架實現遠程服務暴露與調用

java 分布式 程序員

一、前言

Spring框架提供了通過HTTP協議實現遠程調用的方式,具體是調用方使用HttpInvokerProxyFactoryBean生成一個代理對象,通過代理對象遠程通過http服務調用服務提供方法的服務並,服務提供方通過HttpInvokerServiceExporter在服務端暴漏遠程調用接口。

二、遠程服務暴露

2.1 簡單使用

第一步需要定義需要暴露的服務接口和實現
public interface UserServiceBo {
String sayHello(String name);
String sayHello2(String name);
String testPojo(Person person);

}
public class UserServiceImpl implements UserServiceBo{

@Override
public String sayHello(String name) {

    return name; 
}

@Override
public String sayHello2(String name) {

    return name;
}

@Override
public String testPojo(Person person) {
    return JSON.toJSONString(person);
}  

}
第二步創建服務導出HttpInvokerServiceExporter的實例

<bean id="userService" class="com.test.UserServiceImpl" />
<bean name="useServiceExporter" class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
<property name="service" ref="userService" />
<property name="serviceInterface" value="com.test.UserServiceBo" />
</bean>
第三步 暴露遠程服務的URL
<bean id="simpleUrlRequestHandler"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="alwaysUseFullPath" value="true" />
<property name="urlMap">
<map>
<entry key="/remote/test/userService" value-ref="useServiceExporter" />
</map>
</property>
</bean>
註意這個bean要配置到dispatcher類的配置文件裏面。

2.2 原理

image.png

三、遠程服務調用

3.1 簡單使用

HttpInvokerProxyFactoryBean factoryBean = new HttpInvokerProxyFactoryBean();
factoryBean.setServiceUrl("http://127.0.0.1:7001/test/userService.do");
factoryBean.setServiceInterface(UserServiceBo.class);
factoryBean.afterPropertiesSet();
UserServiceBo userService = (UserServiceBo) factoryBean.getObject();

    System.out.println(userService.sayHello("jiaduo"));

3.2 原理

image.png

四、總結

Spring框架提供了通過HTTP協議實現遠程調用的方式,我們可以通過重寫invoker自定義http請求header和body傳遞一些信息到服務暴露端,比如函數簽名指,序列化協議等。
通過重寫exporter可以進行鑒權操作,比如進行函數簽名校驗,然後可以定制反序列化方式。

使用Spring框架實現遠程服務暴露與調用