主要依赖
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-dependencies-zookeeper</artifactId>
<version>3.0.5</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo</artifactId>
<version>3.0.5</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-x-discovery</artifactId>
<version>5.2.0</version>
</dependency>
provider(服务提供者)
自定义配置文件:dubbo.properties
dubbo.application.name=provider-test
# 注册中心
dubbo.registry.address=zookeeper://127.0.0.1:2181
# 使用协议
dubbo.protocol.name=dubbo
# 服务通信端口
dubbo.protocol.port=20881
dubbo.provider.token=true
服务接口
// 消费接口需要与提供者的接口全路径相同
public interface HelloService {
String send();
}
@DubboService(version = "1.0.0")
public class HelloServiceImpl implements HelloService {
@Override
public String send() {
String uuid = UUID.randomUUID().toString();
return "dubbo-" + uuid;
}
}
配置类
@Configuration
//服务接口实现所在包
@EnableDubbo(scanBasePackages = "com.example.api")
@PropertySource("classpath:/dubbo.properties")
public class DubboProviderConfig {
}
启动类
public class ProviderTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DubboProviderConfig.class);
context.start();
while (true);
}
}
consumer(服务消费者)
自定义配置文件:dubbo.properties
dubbo.application.name=consumer-test
dubbo.registry.address=zookeeper://127.0.0.1:2181
# 超时时间
dubbo.consumer.timeout=3000
# 重试次数
dubbo.consumer.retries=2
# 启动时没有提供者时不报错
dubbo.consumer.check=false
#关闭注册中心启动时检查
dubbo.registry.check=false
服务接口
// 消费接口需要与提供者的接口全路径相同
public interface HelloService {
String send();
}
服务调用
@Service
public class RpcService {
// 对于服务提供的version
@DubboReference(version = "1.0.0")
private HelloService helloService;
public void get(){
String res = helloService.send();
System.out.println(res);
}
}
配置类
@Configuration
//开启基于注解的dubbo功能
@EnableDubbo(scanBasePackages = "com.example.api")
@PropertySource("classpath:/dubbo.properties")
// 扫描@DubboReference所在包
@ComponentScan(value = {"com.example.consumertest.service"})
public class DubboConsumerConfig {
}
启动类
public class ConsumerTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DubboConsumerConfig.class);
context.start();
context.getBean(RpcService.class).get();
}
}