公共接口主要用于存放接口对象,这里我们只创建一个服务层的接口IndexService用于远程调用服务的测试
package com.example.dubboapi.service; public interface IndexService { String echo(); }
2.创建服务提供者provider 2.1.导入依赖
主要导入与dubbo相关的包,因为笔者使用的服务注册中心是zookeeper,因此还需要导入与zookeeper相关依赖。
org.springframework.boot spring-boot-starter-weborg.apache.dubbo dubbo-spring-boot-starter2.7.1 org.apache.dubbo dubbo2.7.1 org.apache.dubbo dubbo-dependencies-zookeeper2.7.1 pom com.example dubbo-api0.0.1-SNAPSHOT
2.2.编写配置文件
填写基本的端口信息,以及与dubbo注册中心相关的信息即可(笔者这里使用zookeeper作为注册中心)
server: port: 9901 dubbo: application: id: dubbo-provider name: dubbo-provider registry: address: zookeeper://127.0.0.1:2181
2.3.编写测试类
编写一个测试类IndexServiceImpl用于测试远程调用服务。
需要注意的是: @Service注解使用的并不是Spring下的注解,而是dubbo包下的注解。因为需要被调用的服务类需要交给dubbo去管理,而不是Spring。
package com.example.dubboprovider.service; import com.example.dubboapi.service.IndexService; import org.apache.dubbo.config.annotation.Service; @Service public class IndexServiceImpl implements IndexService { @Override public String echo() { return "This is IndexServiceImpl echo()"; } }
2.4.编写启动类
启动类加上@EnableDubbo注解即可
@SpringBootApplication @EnableDubbo public class DubboProviderApplication { public static void main(String[] args) { SpringApplication.run(DubboProviderApplication.class, args); } }
3.创建服务消费者consumer
消费者模块与提供者模块需要完成的 *** 作类似。
3.1.导入依赖依赖的导入也与提供者模块一致
org.springframework.boot spring-boot-starter-weborg.apache.dubbo dubbo-spring-boot-starter2.7.1 org.apache.dubbo dubbo2.7.1 org.apache.dubbo dubbo-dependencies-zookeeper2.7.1 pom com.example dubbo-api0.0.1-SNAPSHOT
3.2.编写配置文件
与提供者模块一样,配置端口信息,以及dubbo注册中心信息即可。
server: port: 9000 dubbo: application: name: dubbo-consumer registry: address: zookeeper://127.0.0.1:2181
3.3.编写测试类
因为这个模块是消费者模块,因此我们需要编写一个控制层对象IndexController,并在其中远程调用提供者的服务层对象IndexServiceImpl完成远程调用服务的测试。
需要注意的是: 在平常使用spring的时候,我们习惯使用@Autowired对属性完成注入,但由于在上面的 *** 作中,我们将需要被远程调用的对象交给了dubbo管理,因此需要dubbo来完成属性的注入,而对应的注解就是@Reference。
package com.example.dubboconsumer.controller; import com.example.dubboapi.service.IndexService; import org.apache.dubbo.config.annotation.Reference; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class IndexController { @Reference private IndexService service; @RequestMapping("/") public String index() { return service.echo(); } }
4.开始测试
- 启动zookeeper(如果你未完成zookeeper的安装,可以回看笔者此前的文章《Windows下安装Zookeeper》);
- 启动服务提供者模块dubbo-provider;
- 启动服务消费者模块dubbo-consumer;
- 访问消费者模块中对应的接口:http://localhost:9000/
当页面显示提供者模块服务层对象返回的字符串This is IndexServiceImpl echo()时,代表dubbo已经成功调用到了远程服务~!!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)