配置文件application.yml,要注意的是registry.address的值zookeeper://192.168.50.43:2181,这就是Zookeeper注册中心的配置:
dubbo: application: #application-name 本模块名字 name: springboot-zk-provider registry: address: zookeeper://192.168.50.43:2181 protocol: name: dubbo port: 20880编写服务实现类DemoServiceImpl.java,注意@Service注解将当前类的实例作为远程服务对外暴露:
package com.bolingcavalry.springbootzkprovider; import com.bolingcavalry.dubbopractice.service.DemoService; import lombok.extern.slf4j.Slf4j; import org.apache.dubbo.config.annotation.Service; import org.apache.dubbo.rpc.RpcContext; @Slf4j @Service public class DemoServiceImpl implements DemoService { @Override public String sayHello(String name) { log.info("I'm springboot-zk-provider, Hello " + name + ", request from consumer: " + RpcContext.getContext().getRemoteAddress()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } return "I'm springboot-zk-provider, Hello " + name + ", response from provider: " + RpcContext.getContext().getLocalAddress(); } }编写SpringBoot启动类SpringBootZKProviderApplication.java,注意要添加@EnableDubbo注解:
package com.bolingcavalry.springbootzkprovider; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @EnableDubbo public class SpringBootZKProviderApplication { public static void main(String[] args) { SpringApplication.run(SpringBootZKProviderApplication.class, args); } }至此服务提供方编码完成,直接在IDEA上运行SpringBootZKProviderApplication类即可启动服务,启动成功后的日志输出如下图,如红框所示,已连上了Zookeeper:
编码(服务消费方)现在网络上已经有了服务,咱们再来编写服用消费方的代码,一共要创建6个文件,创建顺序和功能如下表:
创建顺序 文件名 作用1 pom.xml 工程的pom文件
2 src/main/resources/application.yml 配置文件
3 RemoteInvokeServiceImpl.java service层,在这里远程调用服务提供方的服务
4 DemoController.java web接口类,对外提供web服务
5 SwaggerConfig.java swagger配置类,便于通过页面测试接口
6 SpringBootZKConsumerApplication.java 启动类
完整的文件位置如下图:
接下来逐个创建上述文件;