SpringBoot 整合 Dubbo
主要依赖
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</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(服务提供者)
application.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 = "2.0.0")
public class HelloServiceImpl implements HelloService {
@Override
public String send() {
String uuid = UUID.randomUUID().toString();
return "dubbo-" + uuid;
}
}
启动类
//服务接口实现所在包
@EnableDubbo(scanBasePackages = "com.example.api")
@SpringBootApplication
public class ProviderTestApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderTestApplication.class, args);
}
}
consumer(服务消费者)
application.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 = "2.0.0")
private HelloService helloService;
public void get(){
String res = helloService.send();
System.out.println(res);
}
}
启动类
@EnableDubbo
@SpringBootApplication
public class ConsumerTestApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(ConsumerTestApplication.class, args);
context.getBean(RpcService.class).get();
}
}