Dubbo的功能除了基本的RPC职能外,核心功能便是监控及服务注册。
provider服务
首先创建一个maven工程:springboot-provider,再添加一个moven模块:sample-api,再里面创建一个接口:IHelloService
public interface IHelloService {
String sayHello(String name);
}
然后mvn install
springboot-provide这个顶层项目,这会在本地的maven仓库安装这父子两个库。
再添加一个springboot模块:sample-provider,来实现IHelloService
接口
@DubboService
public class HelloServiceImpl implements IHelloService {
@Value("${dubbo.application.name}")
private String serviceName;
@Override
public String sayHello(String s) {
return String.format("[%s]: Hello,%s", serviceName, s);
}
}
在pom.xml添加依赖
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.7.7</version>
</dependency>
<dependency>
<groupId>org.example</groupId>
<artifactId>sample-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
在application.properties添加dubbo的配置
dubbo.application.name=jesse-dubbo
dubbo.protocol.port=20880
dubbo.protocol.name=dubbo
dubbo.registry.address=N/A
启动类:
@DubboComponentScan
@SpringBootApplication
public class SampleProviderApplication {
public static void main(String[] args) {
SpringApplication.run(SampleProviderApplication.class, args);
}
}
provider服务就启动了~
consumer服务
新建一个springboot项目:springboot-consumer
,在pom.xml添加依赖,同上。同样也要在application.properties添加dubbo的配置,不过最少只要配置name就行
dubbo.application.name=springboot-consumer
启动类:
@SpringBootApplication
public class SpringbootConsumerApplication {
@DubboReference(url = "dubbo://127.0.0.1:20880")
private IHelloService helloService;
public static void main(String[] args) {
SpringApplication.run(SpringbootConsumerApplication.class, args);
}
@Bean
public ApplicationRunner runner(){
return args -> System.out.println(helloService.sayHello("Mic"));
}
}
完~