dubbo集成spring

 

dubbo集成spring

1.项目依赖


<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo</artifactId>
<version>2.7.5</version>
</dependency>

<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-dependencies-zookeeper</artifactId>
<version>2.7.5</version>
<type>pom</type>
</dependency>

<dependency>
<groupId>cn.wjs</groupId>
<artifactId>dubbo-xml-interface</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>

2.服务提供者

 

resource/spring下添加dubbo-provider.xml:

通过 Spring 配置引用远程服务


<dubbo:application metadata-type="remote" name="demo-provider"/>
<dubbo:metadata-report address="zookeeper://127.0.0.1:2181"/>
<!-- zk注册中心 -->
<dubbo:registry address="zookeeper://127.0.0.1:2181"/>

<dubbo:protocol name="dubbo"/>

<bean id="demoService" class="cn.wjs.DemoServiceImpl"/>
<!-- 生成远程服务代理,可以和本地bean一样使用demoService -->
<dubbo:service interface="cn.wjs.DemoService" ref="demoService"/>
DemoServiceImpl: 
public class DemoServiceImpl implements DemoService {
private static final Logger logger = LoggerFactory.getLogger(DemoServiceImpl.class);

public String sayHello(String name) {
logger.info("aaa");
return "Hello " + name;
}

}
public class Application {
public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/dubbo-provider.xml");
context.start();
System.in.read();
}
}

 

3.服务消费者

resource/spring目录下添加dubbo-consumer.xml

通过 Spring 配置引用远程服务

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:dubbo="http://dubbo.apache.org/schema/dubbo"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd">
<!-- 消费方应用名,用于计算依赖关系,不是匹配条件,不要与提供方一样 -->
<dubbo:application name="demo-consumer"/>

<dubbo:registry address="zookeeper://127.0.0.1:2181"/>
<!-- 生成远程服务代理,可以和本地bean一样使用demoService -->
<dubbo:reference id="demoService" check="false" interface="cn.wjs.DemoService"/>

</beans>

applicaiton: 

public class Application {
/**
* In order to make sure multicast registry works, need to specify '-Djava.net.preferIPv4Stack=true' before
* launch the application
*/
public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/dubbo-consumer.xml");
context.start();
DemoService demoService = (DemoService) context.getBean("demoService"); // 获取远程服务代理
String hello = demoService.sayHello("world"); // 执行远程方法
System.out.println(hello); // 显示调用结果
}
}

 

4.启动zookeeper注册中心

zookeeper3.4.14/bin/zkServer.sh start  

5.分别启动服务端和消费端

消费者启动成功后输出: hello world

 

github地址: 

服务端: dubbo-xml-provider

消费端: dubbo-xml-consumer

接口: dubbo-xml-interface

https://github.com/wujinsen/dubbo-learning

 

 

 

posted @ 2020-03-29 11:17  雨下个不停  阅读(812)  评论(0编辑  收藏  举报