【JAVA】Spring HTTP Invoker 远程服务调用

远程服务调用在实际的项目中很常用,在多重方式中,HTTP应该算是比较常用的,对客户端来说也很方便

但是spring http invoker只支持JAVA语言,结构简单,只依赖与spring框架本身。

首先我们来看服务端(依赖于WEB容器来启动,tomcat/jetty)

【JAVA】Spring HTTP Invoker 远程服务调用_第1张图片

定义接口和接口实现类,这里的接口和下面的客户端的接口是同一个

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;
	}
    
}


再来看客户端

【JAVA】Spring HTTP Invoker 远程服务调用_第2张图片

配置文件

<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容器启动即可



你可能感兴趣的:(【JAVA】Spring HTTP Invoker 远程服务调用)