1. 程式人生 > >【JAVA】Spring HTTP Invoker 遠端服務呼叫

【JAVA】Spring HTTP Invoker 遠端服務呼叫

遠端服務呼叫在實際的專案中很常用,在多重方式中,HTTP應該算是比較常用的,對客戶端來說也很方便

但是spring http invoker只支援JAVA語言,結構簡單,只依賴與spring框架本身。

首先我們來看服務端(依賴於WEB容器來啟動,tomcat/jetty)


定義介面和介面實現類,這裡的介面和下面的客戶端的介面是同一個

remote-servlet.xml

<bean name="/my" class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
        <property name="service" ref="myServiceImpl" />
        <property name="serviceInterface" value="com.chiwei.MyService" />
    </bean>
    <bean id="myServiceImpl" class="com.chiwei.MyServiceImpl" />

web.xml
<servlet>
		<servlet-name>service</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:config/remote-servlet.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>service</servlet-name>
		<url-pattern>/service/*</url-pattern>
	</servlet-mapping>
注意這裡的HttpInvokerServiceExporter的bean配置,name就是客戶端訪問時URL的最後部分

web.xml中的url-pattern就是URL中的前一部分

實現類

public class MyServiceImpl implements MyService {
    
	public String fun(String param) {
		return "Hello " + param;
	}
    
}
再來看客戶端



配置檔案

<bean id="userService" class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean" >
        <property name="serviceUrl" value="http://localhost:8888/service/my"/>
        <property name="serviceInterface" value="com.chiwei.MyService" />
    </bean>
這裡的ip port依賴於部署的環境,port就是web容器裡的配置埠

測試類

public class Test {
   public static void main(String[] args) {
       ApplicationContext ac = new ClassPathXmlApplicationContext(
                       "classpath:config/application-context.xml");
       MyService service = (MyService)ac.getBean("userService");
       System.out.println(service.fun(" chiwei !"));
   }
}

Hello  chiwei !

服務端通過tomcat容器啟動即可