Dubbo 使用概念
2018-05-06 本文已影响0人
tony_0c73
https://blog.csdn.net/flashflight/article/details/43939275
简介
接入步骤
- 接口定义
- 接口实现,暴露接口
- 消息端引入服务,调用服务
接口定义
package com.test;
public interface DemoService{
String sayHello(String name);
}
生产者
接口实现
package com.test;
import org.springframework.stereotype.Service;
import com.test.DemoService;
@Service("demoService")
public class DemoServiceImpl implements DemoService{
@Override
public String sayHello(String name) {
// TODO Auto-generated method stub
return name;
}
}
声明暴露服务
<?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" />
<!-- 使用zookeeper注册中心暴露服务地址 -->
<dubbo:registry address="zookeeper://127.0.0.1:2181" />
<!-- 用dubbo协议在20880端口暴露服务 -->
<dubbo:protocol name="dubbo" port="20880" />
<!-- 声明需要暴露的服务接口 -->
<dubbo:service interface="com.test.DemoService" ref="demoService" />
</beans>
消费者
在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" />
<!-- 使用multicast广播注册中心暴露发现服务地址 -->
<dubbo:registry protocol="zookeeper" address="zookeeper://127.0.0.1:2181" />
<!-- 生成远程服务代理,可以和本地bean一样使用demoService -->
<dubbo:reference id="demoService" interface="com.test.DemoService" />
</beans>
调用服务
import java.io.IOException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "classpath:springmvc.xml" });
context.start();
DemoService demoService = (DemoService) context.getBean("demoService");
System.out.println(demoService.sayHello("哈哈哈"));
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
}