引入Dubbo依赖(版本自定义即可)
<dependencies>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo</artifactId>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-registry-zookeeper</artifactId>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-registry-nacos</artifactId>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-rpc-dubbo</artifactId>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-remoting-netty4</artifactId>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-serialization-hessian2</artifactId>
</dependency>
<!-- 该依赖为接口依赖,自定义即可 -->
<dependency>
<groupId>king-parent</groupId>
<artifactId>dubbo-filter-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
Provider
-
添加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
-
添加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); } } }