Dubbo快速入门(附案例)
以下是一个简单的Dubbo入门示例,演示了如何使用Dubbo进行服务提供和服务消费。
- 定义服务接口:
public interface GreetingsService {
String sayHello(String name);
}
- 实现服务:
public class GreetingsServiceImpl implements GreetingsService {
@Override
public String sayHello(String name) {
return "Hello, " + name + "!";
}
}
- 配置服务提供者(provider.xml):
<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"/>
<dubbo:registry address="zookeeper://127.0.0.1:2181"/>
<dubbo:protocol name="dubbo" port="20880"/>
<dubbo:service interface="GreetingsService" ref="greetingsService" />
<bean id="greetingsService" class="GreetingsServiceImpl"/>
</beans>
- 配置服务消费者(consumer.xml):
<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-consumer"/>
<dubbo:registry address="zookeeper://127.0.0.1:2181"/>
<dubbo:reference id="greetingsService" interface="GreetingsService" />
</beans>
- 服务提供者启动代码:
public class Provider {
public static void main(String[] args) throws IOException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"provider.xml"});
context.start();
System.in.read(); // 防止提供者立即退出
}
}
- 服务消费者调用代码:
public class Consumer {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"consumer.xml"});
context.start();
Gre
评论已关闭