1、客户端配置文件 consumer.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd "> <!-- consumer application name --> <dubbo:application name="Frame" /> <!-- registry address, used for consumer to discover services --> <dubbo:registry address="multicast://224.5.6.7:1234" /> <!-- which service to consume? --> <dubbo:reference id="helloService" interface="merchant.shop.service.IHelloService" /> </beans>
这里dubbo的地址需要与下面服务端的一致
客服端只有action 和 service 的接口 ,没有service 的实现类
需要启动的文件有下面的两个:
package com.sitech.comm.dubbo; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Consumer { public static ClassPathXmlApplicationContext context = null; public static ClassPathXmlApplicationContext singleton() { if (context == null) { context = new ClassPathXmlApplicationContext(new String[] {"consumer.xml"}); context.start(); } return context; }; }
package com.sitech.comm.dubbo; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import com.sitech.comm.log.LogWritter; public class ConsumerInit extends HttpServlet { public void init() throws ServletException { try { System.out.println("初始化dubbo客户端"); Consumer.singleton(); } catch (Exception e) { System.out.println("初始化dubbo客户端失败"); } } }
在 web.xml 中添加个启动:
<servlet> <servlet-name>ConsumerInit</servlet-name> <servlet-class>com.sitech.comm.dubbo.ConsumerInit</servlet-class> <load-on-startup>1</load-on-startup> </servlet>
acton 中的使用方法:
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import merchant.shop.service.IHelloService; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; import com.sitech.comm.dubbo.Consumer; public class TestAction extends AbstractController{ @Override protected ModelAndView handleRequestInternal(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception { IHelloService helloService = (IHelloService) Consumer.singleton().getBean("helloService"); helloService.sayHello(); return null; } }
sevice 接口如下:
package merchant.shop.service; public interface IHelloService { public String sayHello(); }