1. pom.xml添加maven依赖
<!--spring-boot-starter-dubbo-->
<dependency>
<groupId>com.gitee.reger</groupId>
<artifactId>spring-boot-starter-dubbo</artifactId>
<version>1.1.1</version>
</dependency>
<!-- 引入zookeeper,去除其中的log4j,否则会因为日志原因导致堆栈溢出 -->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.10</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--Dubbo的API-->
<dependency>
<groupId>com.test</groupId>
<artifactId>test-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
2. application.yml增加dubbo配置信息
spring:
dubbo:
application:
name: demo-consumer
base-package: com.test.api # dubbo服务发布者所在的包
registry:
address: 127.0.0.1 # zookeeper注册中心的地址
port: 2181 # zookeeper注册中心的端口
protocol: zookeeper
register: true
protocol:
name: dubbo
port: 20880
accesslog: true
provider:
retries: 1
delay: -1
3. 启动类增加Dubbo注解
@SpringBootApplication
@EnableDubbo
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
4. 生产者service接口定义
package com.demo.api;
public interface TestServiceApi {
/**
* 输出问候
*/
void sayHello();
}
5. 生产者接口实现(注意@Service的包路径是dubbo的包路径, 不是Spring的)
package com.demo.api.impl;
import com.alibaba.dubbo.config.annotation.Service;
@Service
public class TestServiceApiImpl implements TestServiceApi {
/**
* 输出问候
*/
@Override
public void sayHello() {
return "Hello world!";
}
}
6. 消费者调用示例
import com.alibaba.dubbo.config.annotation.Reference;
import com.demo.api.TestServiceApi;
@Reference
private TestServiceApi testServiceApi;
public void hello() {
String result = testServiceApi.sayHello();
System.out.println("result = " + result);
}