一、安装zookeeper
详细可以百度!
二、公共接口
public interface IDemoService
{
public abstract String gerStr(String paramString);
}
三、服务端
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>
四、客户端
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>