No1 先创建一个简单的maven项目。 在pom导入相对应的jar包
<!--Dubbo依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<version>2.6.0</version>
</dependency>
<!--添加Zookeeper依赖-->
<dependency>
<groupId>com.github.sgroschupf</groupId>
<artifactId>zkclient</artifactId>
<version>0.1</version>
</dependency>
然后在当前的maven项目新建一个Module 名字随便(服务生产者)忽略命名不规范
在这里我们new一个接口和实现类
package com.lin.service;
public interface GetUname {
String getUname(int id);
}
package com.lin.service;
public interface GetUname {
String getUname(int id);
}
新建一个Spring.xml 在里面添加我们需要暴露的服务以及设置zk
<?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的应用名称-->
<dubbo:application name="dubbo-provider"/>
<!--配置注册中心地址。以及Zookeeper-->
<dubbo:registry address="zookeeper://localhost:2181"/>
<!--配置Dubbo的协议和端口号。默认是dubbo和20880-->
<dubbo:protocol name="dubbo" port="20880"/>
<!--配置你需要暴露的服务以及他的实现类-->
<dubbo:service interface="com.lin.service.GetUname" ref="getuname"/>
<bean id="getuname" class="com.lin.GetUnameimpl"/>
</beans>
新建一个Main方法来使用当前这个
这里使用死循环是避免运行完毕jvm回收。从而关闭了服务
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext("classpath:applicationContext-dubbo.xml");
while (true){
}
}
}
生产者就配置完成了。接下来配置消费者
在消费者这里配置一个Spring.xml(在Maven导入你生产者的jar包。)
<?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"/>
<dubbo:registry address="zookeeper://localhost:2181"/>
<dubbo:reference id="getuname" interface="com.lin.service.GetUname"/>
</beans>
接着新建一个Main方法
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.GetUname;
public class Main {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext("classpath:applicationContext-dubbo.xml");
GetUname g=
(GetUname) applicationContext.getBean("getuname");
String uname = g.getUname(10);
System.out.println(uname);
while (true){
}
}
}
Main结果:
id:10
Main1结果:
id:10
如果遇到consumer无法绑定端口。在配置文件里面加一句
dubbo.protocol.port=-1
如果遇到多个服务。刷新报500并且找不到绑定方法。但是重复刷新有几次能过的。在消费者配置文件里面添加一句
dubbo.provider.timeout=10000