Main方法启动dubbo,并使用dubbo命令行模拟客户端测试

转载请标注原文地址:https://lilyssh.cn/dubbo/dubbo-main-reload/

1、引入maven包

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<version>2.5.3</version>
</dependency>
<dependency>
<groupId>com.github.sgroschupf</groupId>
<artifactId>zkclient</artifactId>
<version>0.1</version>
</dependency>

2、添加配置文件

resource/META-INF下建个xml, 例如:demo-provider.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?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="demo-provider" owner="mic"/>

<!--dubbo这个服务所要暴露的服务地址所对应的注册中心-->
<dubbo:registry protocol="zookeeper" address="qianxunclub.com:2181"/>

<!--当前服务发布所依赖的协议;webService、Thrift、Hessian、http-->
<dubbo:protocol name="dubbo" port="20880"/>
</beans>

3、添加对外抛出的接口

1
2
3
public interface DemoService {
String sayHello(String name);
}
1
2
3
4
5
6
public class DemoServiceImpl implements DemoService {
@Override
public String sayHello(String name) {
return "hello:"+name;
}
}

demo-provider.xml配置文件中,添加 对外抛出接口:

1
2
3
4
5
6
7
<!-- 注入bean -->
<bean id="demoService" class="com.qianxunclub.demo.dubbo.DemoServiceImpl"/>

<!--服务发布的配置,需要暴露的服务接口-->
<dubbo:service
interface="com.qianxunclub.demo.dubbo.DemoService"
ref="demoService"/>

4、调用dubbo的main方法

1
2
3
4
5
6
import com.alibaba.dubbo.container.Main;
public class DubboMain {
public static void main(String[] args) {
Main.main(args);
}
}

5、检查服务注册是否成功

使用 telnet 模拟调用dubbo服务,端口为demo-provider.xml里配置的dubbo端口。

1
telnet localhost 20880

如果连接成功,会看到

1
2
3
4
5
Trying ::1...
Connected to localhost.
Escape character is '^]'.

dubbo>

使用ls查看所有服务

1
2
dubbo>ls
com.qianxunclub.demo.dubbo.DemoService

如果出现这个接口,代表注册成功。

6、模拟客户端调用

使用telnet模拟调用服务
使用cd进入到com.qianxunclub.demo.dubbo.DemoService中,并使用ls查看服务里的方法

1
2
3
4
5
6
7
dubbo>cd com.qianxunclub.demo.dubbo.DemoService
Used the com.qianxunclub.demo.dubbo.DemoService as default.
You can cancel default service by command: cd /
dubbo>ls
Use default service com.qianxunclub.demo.dubbo.DemoService.

sayHello

使用invoke模拟客户端调用服务

1
2
3
4
dubbo>invoke sayHello("world")
Use default service com.qianxunclub.demo.dubbo.DemoService.
"hello:world"
elapsed: 1 ms.

大功告成!

本文由 lilyssh创作。可自由转载、引用,但需署名作者且注明文章出处。


当前网速较慢或者你使用的浏览器不支持博客特定功能,请尝试刷新或换用Chrome、Firefox等现代浏览器