dubbo 的基本使用
主要依赖
<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();
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话