dubbo-consumer调用方常见调用方式
引言
dubbo作为当今比较流行的微服务架构,现已被各互联网、技术公司普遍引用,对很多服务都模块化调用,有些功能点转测往往需要单独写调用代码,而不是像之前一些,在原来的项目中,点、点、就出来了,对有些不太深入java的测试小哥哥、小姐姐还是有一些难度,对此本人整理现在比较常用的几种dubbo微服务调用方式,希望对初学者和入门的同事有些帮助。
xml原生加载法
第一种:xml原生加载法,简单实用,对一些只是调用测试,不用深入写功能的场景,非常实用,话不多说,我们看代码。
- 首先引包:
<!-- https://mvnrepository.com/artifact/com.alibaba/dubbo -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
<version>0.9</version>
</dependency>
如果提供方不是注入zk管理的,可以不用zkclient,我这里是zk注入管理,所以要引用。
- 写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
http://code.alibabatech.com/schema/dubbo
http://code.alibabatech.com/schema/dubbo ">
<!-- 提供方应用信息,用于计算依赖关系 -->
<dubbo:application name="operation-consumer" />
<!-- 使用zk注册管理服务地址 -->
<dubbo:registry protocol="zookeeper" address="*.*.*.*:2181" />
<dubbo:consumer group="myGroup" />
<!-- 生成远程服务代理, -->
<dubbo:reference id="myService" interface="服务接口类全限定路径.MyService" retries="0" timeout="6000"/>
</beans>
- 写调用demo
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"dubbo-consumer.xml"});
context.start();
MyService mySerivce= (MyService) context.getBean("myService");
testDosomething(mySerivce);
context.close();
}
public static void testDosomething(MyService service){
service.doSomething();
}
以上就实现了简单调用是不是很easy!
SpringBoot项目调用
第二种:SpringBoot项目调用
-
同理引包,同上;
-
写dubbo-consumer.xml配置,同上一样即可;
-
在SpringBoot启动类Appliaction,加载
@ImportResource({"classpath:config/dubbo-consumer.xml"})
- 写SpringBoot引用
@Resource
@Qualifier(value = "myService")
private MyService myService;
这里有很人会用@Autowired,用了也没有错,但我们的服务类是在配置中,用了一开发工具会报加载不了错误,虽然不影响使用,但不美观。
- 最后写SpringBoot测试类
@SpringBootTest
@RunWith(SpringRunner.class)
public class BoottestApplicationTests {
@Resource
@Qualifier(value = "myService")
private MyService myService;
@Test
public void testPaybillQuery(){
myService.toSomething();
}
}
好了,以上两种方式介绍完了,是不是很简单,应该对很多入门使用dubbo服务的同学有帮助