首先一定确保zookeeper正常工作
为了简化代码,可以把需要其他服务调用的接口,抽取为公共接口模块dubbo-common-service,
public interface TestService {public String clientTest();
}
导入dubbo、zookeeper依赖
org.apache.dubbo dubbo-spring-boot-starter 3.0.5 org.apache.curator curator-framework 5.2.0 org.apache.curator curator-recipes 5.2.0 org.apache.curator curator-x-discovery 5.2.0 com.psh dubbo-common-service 1.0
配置文件为:
server:port: 6610 #端口
dubbo:application:name: dubbo-client #别名registry:address: zookeeper://192.168.158.159:2181 #zookeeper 地址 + 端口timeout: 230000 # 如果zookeeper是放在远程服务器上超时时间请设置长一些,不然很容易超时连接失败protocol:port: 20881 # 不同服务使用不同端口,不然会报错name: dubbo
提供方实现接口并暴露服务,在接口实现类增加@DubboService
@DubboService
public class ClientServiceImpl implements TestService {@Overridepublic String clientTest() {return "远程调用成功";}
}
启动类加上@EnableDubbo
@EnableDubbo
@SpringBootApplication
public class DubboApplicationClient {public static void main(String[] args) {SpringApplication.run(DubboApplicationClient.class);}
}
org.apache.dubbo dubbo-spring-boot-starter 3.0.5 org.apache.curator curator-framework 5.2.0 org.apache.curator curator-recipes 5.2.0 org.apache.curator curator-x-discovery 5.2.0 com.psh dubbo-common-service 1.0
server:port: 6620dubbo:application:name: dubbo-client #别名registry:address: zookeeper://192.168.158.159:2181 #zookeeper 地址 + 端口timeout: 230000 # 如果zookeeper是放在远程服务器上超时时间请设置长一些,不然很容易超时连接失败protocol:port: 20882 # 不同服务使用不同端口,不然会报错name: dubbo
启动类
@EnableDubbo
@SpringBootApplication
public class DubboApplicationServer {public static void main(String[] args) {SpringApplication.run(DubboApplicationServer.class);}
}
controller接口
@RestController
public class DubooServerApplication {@Autowiredprivate ServerService serverService;@GetMapping("/test")public String test(String name){return serverService.serverTest(name);}}
通过本服务的Service 来远程调用接口
public interface ServerService {public String serverTest(String name) ;
}
@Service
public class ServerServiceImpl implements ServerService {@DubboReferenceprivate TestService testService;public String serverTest(String name) {return "返回结果为:"+testService.clientTest()+",参数为:"+name;}}
访问controller接口,得到:

远程调用成功