<dependencies>
<dependency>
<groupId>org.apache.dubbogroupId>
<artifactId>dubboartifactId>
dependency>
<dependency>
<groupId>org.apache.dubbogroupId>
<artifactId>dubbo-registry-zookeeperartifactId>
dependency>
<dependency>
<groupId>org.apache.dubbogroupId>
<artifactId>dubbo-registry-nacosartifactId>
dependency>
<dependency>
<groupId>org.apache.dubbogroupId>
<artifactId>dubbo-rpc-dubboartifactId>
dependency>
<dependency>
<groupId>org.apache.dubbogroupId>
<artifactId>dubbo-remoting-netty4artifactId>
dependency>
<dependency>
<groupId>org.apache.dubbogroupId>
<artifactId>dubbo-serialization-hessian2artifactId>
dependency>
<dependency>
<groupId>king-parentgroupId>
<artifactId>dubbo-filter-apiartifactId>
<version>1.0-SNAPSHOTversion>
dependency>
dependencies>
添加Config类:
@Configuration
@EnableDubbo(scanBasePackages = "com.king.service")
@PropertySource("classpath:/dubbo-provider.properties")
public class ProviderConfig {
@Bean
public RegistryConfig registryConfig() {
RegistryConfig registryConfig = new RegistryConfig();
registryConfig.setAddress("zookeeper://127.0.0.1:2181");
return registryConfig;
}
}
添加dubbo基本配置
dubbo.application.name=service-provider
dubbo.protocol.name=dubbo
dubbo.protocol.port=20880
添加接口实现类
@Service
public class HelloServiceImpl implements HelloService {
@Override
public String sayHello(String name) {
return "hello~" + name;
}
}
添加main函数类
public class ProviderMain {
public static void main(String[] args) throws IOException {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ProviderConfig.class);
context.start();
System.in.read();
}
}
添加consumer配置文件
其中Qos为dubbo自带的检查dubbo服务信息和服务健康的工具,可以设置为关闭或修改端口,我下面操作是修改了默认22222的端口。以免出现和提供者端口冲突情况
dubbo.application.name=service-consumer
dubbo.registry.address=zookeeper://127.0.0.1:2181
#关闭Qos
dubbo.application.qosEnable=true
dubbo.application.qosPort=33333
dubbo.application.qosAcceptForeignIp=false
添加消费端的Config类
@Configuration
@ComponentScan("com.king.call")
@PropertySource("classpath:/dubbo-consumer.properties")
@EnableDubbo
public class ConsumerConfig {
}
添加消费端调用提供端类
@Component
public class ConsumerCall {
@Reference
HelloService helloService;
public String sayHello(String name) {
return helloService.sayHello(name);
}
}
添加consumer端的Main函数
public class ConsumerMain {
public static void main(String[] args) throws IOException {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConsumerConfig.class);
ConsumerCall bean = context.getBean(ConsumerCall.class);
while (true){
System.in.read();
String result = bean.sayHello(" consumer ");
System.out.println(result);
}
}
}