说明
springboot整合dubbo实现远程调用的小demo,dubbo以nacos作为注册中心。
一共3个模块
第一个模块提供api接口。
第二个模块提供接口实现类。
第三个模块远程调用第二个模块的服务。
模块一:sample-api
只定义接口interface。
public interface IHelloService {
String sayHello(String name);
}
模块二:sample-provider
1、依赖模块一,实现interface。并在实现类上添加来自Dubbo的注解@Service,用来发布服务。
import org.apache.dubbo.config.annotation.Service;
@Service
public class HelloServiceImpl implements IHelloService {
@Value("${dubbo.application.name}")
private String serviceName;
@Override
public String sayHello(String name) {
return String.format("[%s]: Hello,%s", serviceName, name);
}
}
2、在application.yml添加dubbo的配置。
dubbo:
application:
name: springboot-provider
protocol:
name: dubbo
port: 20880
#注册中心设置为nacos
registry:
address: nacos://192.168.31.200:8001
provider:
timeout: 1000
3、主启动类添加注解@DubboComponentScan
@DubboComponentScan
@SpringBootApplication
public class SampleProviderApplication {
public static void main(String[] args) {
SpringApplication.run(SampleProviderApplication.class, args);
}
}
4、启动即可
模块二的依赖
<dependencies>
<!--springboot-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.7.3</version>
</dependency>
<!--nacos-->
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-discovery-spring-boot-starter</artifactId>
<version>0.2.4</version>
<exclusions>
<exclusion>
<groupId>com.alibaba.spring</groupId>
<artifactId>spring-context-support</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--dubbo-->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.7.5</version>
</dependency>
<!--引入接口interface模块-->
<dependency>
<groupId>com.chw</groupId>
<artifactId>sample-api</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
模块三:consumer
1、添加模块一的依赖获得interface接口;
2、使用Dubbo提供的@Reference来获得远程代理对象;
public class Consumer {
//使用Dubbo提供的@Reference来获得一个远程代理对象
@Reference(url = "dubbo://192.168.31.200:20880/com.chw.server.sampleapi.service.IHelloService")
private IHelloService helloService;
public static void main(String[] args) {
helloService.sayHello("nihao");
}
}
依赖的是模块一,调用到的是模块二的服务。
模块三的依赖
<dependencies>
<!--dubbo-->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.7.5</version>
</dependency>
<!--引入接口interface模块-->
<dependency>
<groupId>com.chw</groupId>
<artifactId>sample-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!--springboot-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.7.3</version>
</dependency>
</dependencies>