RPC 框架几行代码就够了

本贴最后更新于 2990 天前,其中的信息可能已经时移俗易

转自梁飞的博客(http://javatar.iteye.com/blog/1123915)
Java 代码
/*

  • Copyright 2011 Alibaba.com All right reserved. This software is the
  • confidential and proprietary information of Alibaba.com ("Confidential
  • Information"). You shall not disclose such Confidential Information and shall
  • use it only in accordance with the terms of the license agreement you entered
  • into with Alibaba.com.
    */
    package com.alibaba.study.rpc.framework;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.ServerSocket;
import java.net.Socket;

/**

  • RpcFramework

  • @author william.liangf
    */
    public class RpcFramework {

    /**

    • 暴露服务
    • @param service 服务实现
    • @param port 服务端口
    • @throws Exception
      */
      public static void export(final Object service, int port) throws Exception {
      if (service == null)
      throw new IllegalArgumentException("service instance == null");
      if (port <= 0 || port > 65535)
      throw new IllegalArgumentException("Invalid port " + port);
      System.out.println("Export service " + service.getClass().getName() + " on port " + port);
      ServerSocket server = new ServerSocket(port);
      for(;;) {
      try {
      final Socket socket = server.accept();
      new Thread(new Runnable() {
      @Override
      public void run() {
      try {
      try {
      ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
      try {
      String methodName = input.readUTF();
      Class[] parameterTypes = (Class[])input.readObject();
      Object[] arguments = (Object[])input.readObject();
      ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
      try {
      Method method = service.getClass().getMethod(methodName, parameterTypes);
      Object result = method.invoke(service, arguments);
      output.writeObject(result);
      } catch (Throwable t) {
      output.writeObject(t);
      } finally {
      output.close();
      }
      } finally {
      input.close();
      }
      } finally {
      socket.close();
      }
      } catch (Exception e) {
      e.printStackTrace();
      }
      }
      }).start();
      } catch (Exception e) {
      e.printStackTrace();
      }
      }
      }

    /**

    • 引用服务
    • @param 接口泛型
    • @param interfaceClass 接口类型
    • @param host 服务器主机名
    • @param port 服务器端口
    • @return 远程服务
    • @throws Exception
      */
      @SuppressWarnings("unchecked")
      public static T refer(final Class interfaceClass, final String host, final int port) throws Exception {
      if (interfaceClass == null)
      throw new IllegalArgumentException("Interface class == null");
      if (! interfaceClass.isInterface())
      throw new IllegalArgumentException("The " + interfaceClass.getName() + " must be interface class!");
      if (host == null || host.length() == 0)
      throw new IllegalArgumentException("Host == null!");
      if (port <= 0 || port > 65535)
      throw new IllegalArgumentException("Invalid port " + port);
      System.out.println("Get remote service " + interfaceClass.getName() + " from server " + host + ":" + port);
      return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[] {interfaceClass}, new InvocationHandler() {
      public Object invoke(Object proxy, Method method, Object[] arguments) throws Throwable {
      Socket socket = new Socket(host, port);
      try {
      ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
      try {
      output.writeUTF(method.getName());
      output.writeObject(method.getParameterTypes());
      output.writeObject(arguments);
      ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
      try {
      Object result = input.readObject();
      if (result instanceof Throwable) {
      throw (Throwable) result;
      }
      return result;
      } finally {
      input.close();
      }
      } finally {
      output.close();
      }
      } finally {
      socket.close();
      }
      }
      });
      }

}
用起来也像模像样:

(1) 定义服务接口

Java 代码

/*

  • Copyright 2011 Alibaba.com All right reserved. This software is the
  • confidential and proprietary information of Alibaba.com ("Confidential
  • Information"). You shall not disclose such Confidential Information and shall
  • use it only in accordance with the terms of the license agreement you entered
  • into with Alibaba.com.
    */
    package com.alibaba.study.rpc.test;

/**

  • HelloService

  • @author william.liangf
    */
    public interface HelloService {

    String hello(String name);

}

(2) 实现服务

Java 代码

/*

  • Copyright 2011 Alibaba.com All right reserved. This software is the
  • confidential and proprietary information of Alibaba.com ("Confidential
  • Information"). You shall not disclose such Confidential Information and shall
  • use it only in accordance with the terms of the license agreement you entered
  • into with Alibaba.com.
    */
    package com.alibaba.study.rpc.test;

/**

  • HelloServiceImpl

  • @author william.liangf
    */
    public class HelloServiceImpl implements HelloService {

    public String hello(String name) {
    return "Hello " + name;
    }

}

(3) 暴露服务

Java 代码

/*

  • Copyright 2011 Alibaba.com All right reserved. This software is the
  • confidential and proprietary information of Alibaba.com ("Confidential
  • Information"). You shall not disclose such Confidential Information and shall
  • use it only in accordance with the terms of the license agreement you entered
  • into with Alibaba.com.
    */
    package com.alibaba.study.rpc.test;

import com.alibaba.study.rpc.framework.RpcFramework;

/**

  • RpcProvider

  • @author william.liangf
    */
    public class RpcProvider {

    public static void main(String[] args) throws Exception {
    HelloService service = new HelloServiceImpl();
    RpcFramework.export(service, 1234);
    }

}

(4) 引用服务

Java 代码

/*

  • Copyright 2011 Alibaba.com All right reserved. This software is the
  • confidential and proprietary information of Alibaba.com ("Confidential
  • Information"). You shall not disclose such Confidential Information and shall
  • use it only in accordance with the terms of the license agreement you entered
  • into with Alibaba.com.
    */
    package com.alibaba.study.rpc.test;

import com.alibaba.study.rpc.framework.RpcFramework;

/**

  • RpcConsumer

  • @author william.liangf
    */
    public class RpcConsumer {

    public static void main(String[] args) throws Exception {
    HelloService service = RpcFramework.refer(HelloService.class, "127.0.0.1", 1234);
    for (int i = 0; i < Integer.MAX_VALUE; i ++) {
    String hello = service.hello("World" + i);
    System.out.println(hello);
    Thread.sleep(1000);
    }
    }

}

  • RPC
    16 引用 • 22 回帖
  • Java

    Java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由 Sun Microsystems 公司于 1995 年 5 月推出的。Java 技术具有卓越的通用性、高效性、平台移植性和安全性。

    3194 引用 • 8214 回帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...
  • wugy

    感谢分享,看完才明白 rpc 原来也没这么复杂,重点是 socket 和动态代码,写的精辟!!!

  • 其他回帖
  • Tnima

    抄袭转载过来的,这原本是 dubbo 作者当年写的 csdn 博客

  • lijp

    感谢分享

  • someone

    请看正文第一行

推荐标签 标签

  • 叶归
    5 引用 • 16 回帖 • 9 关注
  • SpaceVim

    SpaceVim 是一个社区驱动的模块化 vim/neovim 配置集合,以模块的方式组织管理插件以
    及相关配置,为不同的语言开发量身定制了相关的开发模块,该模块提供代码自动补全,
    语法检查、格式化、调试、REPL 等特性。用户仅需载入相关语言的模块即可得到一个开箱
    即用的 Vim-IDE。

    3 引用 • 31 回帖 • 116 关注
  • Oracle

    Oracle(甲骨文)公司,全称甲骨文股份有限公司(甲骨文软件系统有限公司),是全球最大的企业级软件公司,总部位于美国加利福尼亚州的红木滩。1989 年正式进入中国市场。2013 年,甲骨文已超越 IBM,成为继 Microsoft 后全球第二大软件公司。

    107 引用 • 127 回帖 • 355 关注
  • GAE

    Google App Engine(GAE)是 Google 管理的数据中心中用于 WEB 应用程序的开发和托管的平台。2008 年 4 月 发布第一个测试版本。目前支持 Python、Java 和 Go 开发部署。全球已有数十万的开发者在其上开发了众多的应用。

    14 引用 • 42 回帖 • 805 关注
  • 周末

    星期六到星期天晚,实行五天工作制后,指每周的最后两天。再过几年可能就是三天了。

    14 引用 • 297 回帖 • 2 关注
  • 浅吟主题

    Jeffrey Chen 制作的思源笔记主题,项目仓库:https://github.com/TCOTC/Whisper

    1 引用 • 28 回帖
  • AngularJS

    AngularJS 诞生于 2009 年,由 Misko Hevery 等人创建,后为 Google 所收购。是一款优秀的前端 JS 框架,已经被用于 Google 的多款产品当中。AngularJS 有着诸多特性,最为核心的是:MVC、模块化、自动化双向数据绑定、语义化标签、依赖注入等。2.0 版本后已经改名为 Angular。

    12 引用 • 50 回帖 • 502 关注
  • 外包

    有空闲时间是接外包好呢还是学习好呢?

    26 引用 • 233 回帖 • 1 关注
  • 学习

    “梦想从学习开始,事业从实践起步” —— 习近平

    172 引用 • 516 回帖
  • OneNote
    1 引用 • 3 回帖
  • 钉钉

    钉钉,专为中国企业打造的免费沟通协同多端平台, 阿里巴巴出品。

    15 引用 • 67 回帖 • 296 关注
  • CongSec

    本标签主要用于分享网络空间安全专业的学习笔记

    1 引用 • 1 回帖 • 23 关注
  • BookxNote

    BookxNote 是一款全新的电子书学习工具,助力您的学习与思考,让您的大脑更高效的记忆。

    笔记整理交给我,一心只读圣贤书。

    1 引用 • 1 回帖 • 1 关注
  • JRebel

    JRebel 是一款 Java 虚拟机插件,它使得 Java 程序员能在不进行重部署的情况下,即时看到代码的改变对一个应用程序带来的影响。

    26 引用 • 78 回帖 • 677 关注
  • HTML

    HTML5 是 HTML 下一个的主要修订版本,现在仍处于发展阶段。广义论及 HTML5 时,实际指的是包括 HTML、CSS 和 JavaScript 在内的一套技术组合。

    108 引用 • 295 回帖 • 2 关注
  • golang

    Go 语言是 Google 推出的一种全新的编程语言,可以在不损失应用程序性能的情况下降低代码的复杂性。谷歌首席软件工程师罗布派克(Rob Pike)说:我们之所以开发 Go,是因为过去 10 多年间软件开发的难度令人沮丧。Go 是谷歌 2009 发布的第二款编程语言。

    498 引用 • 1395 回帖 • 258 关注
  • 架构

    我们平时所说的“架构”主要是指软件架构,这是有关软件整体结构与组件的抽象描述,用于指导软件系统各个方面的设计。另外还有“业务架构”、“网络架构”、“硬件架构”等细分领域。

    143 引用 • 442 回帖
  • PHP

    PHP(Hypertext Preprocessor)是一种开源脚本语言。语法吸收了 C 语言、 Java 和 Perl 的特点,主要适用于 Web 开发领域,据说是世界上最好的编程语言。

    179 引用 • 408 回帖 • 483 关注
  • RemNote
    2 引用 • 16 回帖 • 9 关注
  • HBase

    HBase 是一个分布式的、面向列的开源数据库,该技术来源于 Fay Chang 所撰写的 Google 论文 “Bigtable:一个结构化数据的分布式存储系统”。就像 Bigtable 利用了 Google 文件系统所提供的分布式数据存储一样,HBase 在 Hadoop 之上提供了类似于 Bigtable 的能力。

    17 引用 • 6 回帖 • 60 关注
  • 京东

    京东是中国最大的自营式电商企业,2015 年第一季度在中国自营式 B2C 电商市场的占有率为 56.3%。2014 年 5 月,京东在美国纳斯达克证券交易所正式挂牌上市(股票代码:JD),是中国第一个成功赴美上市的大型综合型电商平台,与腾讯、百度等中国互联网巨头共同跻身全球前十大互联网公司排行榜。

    14 引用 • 102 回帖 • 318 关注
  • ZeroNet

    ZeroNet 是一个基于比特币加密技术和 BT 网络技术的去中心化的、开放开源的网络和交流系统。

    1 引用 • 21 回帖 • 639 关注
  • CSS

    CSS(Cascading Style Sheet)“层叠样式表”是用于控制网页样式并允许将样式信息与网页内容分离的一种标记性语言。

    199 引用 • 541 回帖 • 1 关注
  • 职场

    找到自己的位置,萌新烦恼少。

    127 引用 • 1708 回帖
  • CAP

    CAP 指的是在一个分布式系统中, Consistency(一致性)、 Availability(可用性)、Partition tolerance(分区容错性),三者不可兼得。

    12 引用 • 5 回帖 • 637 关注
  • MongoDB

    MongoDB(来自于英文单词“Humongous”,中文含义为“庞大”)是一个基于分布式文件存储的数据库,由 C++ 语言编写。旨在为应用提供可扩展的高性能数据存储解决方案。MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。它支持的数据结构非常松散,是类似 JSON 的 BSON 格式,因此可以存储比较复杂的数据类型。

    90 引用 • 59 回帖 • 5 关注
  • Lute

    Lute 是一款结构化的 Markdown 引擎,支持 Go 和 JavaScript。

    28 引用 • 197 回帖 • 27 关注