1、首先、引入相关依赖
org.springframework.boot spring-boot-starter-parent2.6.0 org.apache.dubbo dubbo-spring-boot-starter3.0.4 org.apache.zookeeper zookeeper3.6.3 org.slf4j slf4j-log4j12org.apache.curator curator-x-discovery5.2.0
本项目使用的是zookeeper3.6.3,这几个依赖是必须要引入的,其他依赖根据项目需要进行选择。
2、在服务提供方的模块中创建2个子模块,一个是用来定义服务提供方的接口和pojo类,作为服务提供者和消费者的公共模块,接口代码如下:
public interface ApiHouseResourceService { public int saveHouseResources(HouseResources houseResources); }
另一个模块是用来实现这个接口,并提供相应的功能,查询数据库。这里面定义了2个servie,一个是用来查询数据库,代码如下:
@Service public class HouseResourcesServiceImpl extends ServiceImplimplements IHouseResourcesService { @Override public int saveHouseResources(HouseResources houseResources) { if (StringUtils.isBlank(houseResources.getTitle())){ return -1; } return save(houseResources) ? 1 : 0; } }
另一个用来实现dubbo服务,并注入了查询数据库的service,代码如下
@DubboService(version = "1.0.0") public class ApiHouserResourceServiceImpl implements ApiHouseResourceService{ @Autowired private IHouseResourcesService houseResourcesService; @Override public int saveHouseResources(HouseResources houseResources) { return houseResourcesService.saveHouseResources(houseResources); } }
并且,在当前模块中需要进行如下配置
spring: application: name: itcast-haoke-manage-dubbo-server-house-resources datasource: url: jdbc:mysql://localhost:3306/haoke?serverTimezone=Asia/Shanghai username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver dubbo: scan: basePackages: cn.itcast.haoke.dubbo.server.api protocol: name: dubbo port: 20881 registry: address: zookeeper://127.0.0.1:2181 client: curator
其中,dubbo.scan.basePackages是用来扫描dubbo服务所在的包。
3、在服务消费方需要引入公共模块的接口,进行调用,从而实现dubbo远程调用,代码如下
@Service public class HouseResourcesService { @DubboReference(version = "1.0.0") private ApiHouseResourceService apiHouseResourceService; public boolean save(HouseResources houseResources){ int result = apiHouseResourceService.saveHouseResources(houseResources); return result==1; } }
服务消费者的相关配置如下
server: port: 18080 spring: application: name: itcast-haoke-manage-api-server dubbo: registry: address: zookeeper://127.0.0.1:2181 client: curator
4、实现服务消费者的controller层接口,调用service层,并启动zookeeper和各个服务进行测试。
各个模块的依赖关系如下:
值得注意的是,需要先启动zookeeper,再启动服务提供者,然后启动服务消费者,如果顺序不对,会导致项目运行时报错。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)