1、安裝zookeeperjava
詳細能夠百度!spring
2、公共接口app
public interface IDemoService { public abstract String gerStr(String paramString); }
3、服務端ide
public class DemoServiceImpl implements IDemoService{ @Override public String gerStr(String str) { return str; } }
public class TestDemo { public static void main( String[] args ) throws Exception{ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "dubbo-provider.xml" }); context.start(); System.out.println("按任意鍵退出"); System.in.read(); } }
<!--dubbo-provider.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 "> <dubbo:application name="dubbo-provider-app" /> <!-- 使用zookeeper註冊中心暴露服務地址 --> <dubbo:registry protocol="zookeeper" address="192.168.1.132:2181" /> <dubbo:protocol name="dubbo" port="20880" /> <!-- 聲明須要暴露的服務接口 --> <dubbo:service interface="com.zhdan.common.inter.IDemoService" ref="demoService" /> <!-- 具體的實現bean --> <bean id="demoService" class="com.zhdan.dubbo.server.DemoServiceImpl" /> </beans>
4、客戶端代理
public class ActionTest { public void SayHello(String str){ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "dubbo-consumer.xml" }); context.start(); IDemoService demoService = (IDemoService) context.getBean("demoService"); System.out.println(demoService.gerStr(str)); } }
public class ClientTest { public static void main(String[] args) throws Exception { ActionTest test = new ActionTest(); for(int i = 0; i < 2; i++){ test.SayHello("Hello world!"+i); //Thread.sleep(3000); } } }
<!--dubbo-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 "> <!-- 消費方應用名,用於計算依賴關係,不是匹配條件,不要與提供方同樣 --> <dubbo:application name="dubbo-consumer-app" /> <!-- 使用multicast廣播註冊中心暴露發現服務地址 --> <!-- <dubbo:registry address="multicast://224.5.6.7:1234" /> --> <!-- 使用zookeeper註冊中心暴露服務地址 --> <dubbo:registry protocol="zookeeper" address="192.168.1.132:2181" /> <!-- 生成遠程服務代理,能夠和本地bean同樣使用demoService --> <dubbo:reference id="demoService" interface="com.zhdan.common.inter.IDemoService" /> </beans>