RPC 远程调用

目录

  • 配置
  • 开始使用
  • 高级功能

配置

在 Jboot 中,默认实现了对 Dubbo、motan 的 RPC 调用支持。在使用 RPC 远程调用之前,需要做一些基本的配置。

例如 :

  1. jboot.rpc.type = dubbo
  2. jboot.rpc.callMode = direct
  3. jboot.rpc.directUrl = 127.0.0.1:8000
  • jboot.rpc.type : RPC 的类型,不配置默认为 Dubbo
  • jboot.rpc.callMode : RPC 的调用方式
    • direct : 直联模式
    • registry : 注册中心模式(服务注册和服务发现)
  • jboot.rpc.directUrl : 当 callMode 为 direct 直联模式时,需要配置直联模式的服务器 IP 地址和端口号。

更多的配置请查看 config.md

开始使用

一般情况下,RPC 调用需要以下几个步骤:

  • 1、定义接口
  • 2、编写实现类
  • 3、启动 Server 暴露服务
  • 4、启动客户端、通过 RPC 调用 Server 提供的服务

定义接口

  1. public interface BlogService {
  2. public String findById();
  3. public List<String> findAll();
  4. }

编写实现类

  1. @RPCBean
  2. public class BlogServiceProvider implements BlogService {
  3. @Override
  4. public String findById() {
  5. return "id from provider";
  6. }
  7. @Override
  8. public List<String> findAll() {
  9. return Lists.newArrayList("item1","item2");
  10. }
  11. }

启动 Server 暴露服务

  1. public class DubboServer {
  2. public static void main(String[] args) {
  3. JbootApplication.run(args);
  4. System.out.println("DubboServer started...");
  5. }
  6. }

启动客户端、通过 RPC 调用 Server 提供的服务

  1. @RequestMapping("/dubbo")
  2. public class DubboClient extends JbootController{
  3. public static void main(String[] args) {
  4. //Undertow端口号配置
  5. JbootApplication.setBootArg("undertow.port", "8888");
  6. JbootApplication.run(args);
  7. }
  8. @RPCInject
  9. private BlogService blogService;
  10. public void index() {
  11. System.out.println(blogService);
  12. renderText("blogId : " + blogService.findById());
  13. }
  14. }

高级功能

在以上的示例中,使用到了两个注解:

  • @RPCBean,标示当前服务于RPC服务
  • @RPCInject,RPC注入赋值

虽然以上示例中,@RPCBean@RPCInject 没有添加任何的参数,但实际是他们提供了非常丰富的配置。

以下分别是 @RPCBean@RPCInject 的定义:

RPCBean :

  1. public @interface RPCBean {
  2. int port() default 0;
  3. int timeout() default -1;
  4. int actives() default -1;
  5. String group() default "";
  6. String version() default "";
  7. //当一个Service类实现对个接口的时候,
  8. //可以通过这个排除不暴露某个实现接口
  9. Class[] exclude() default Void.class;
  10. }

RPCInject :

  1. public @interface RPCInject {
  2. int port() default 0;
  3. int timeout() default -1;
  4. int retries() default -1;
  5. int actives() default -1;
  6. String group() default "";
  7. String version() default "";
  8. String loadbalance() default "";
  9. String async() default "";
  10. String check() default "";
  11. }