• node(thrift)


    thrift是一种跨语言的RPC框架,据说uber采在node.js项目中采用thrfit后,比原有的http+json的方式提高近20倍的性能。

    所谓的RPC本质上就是客户端将需要调用的方法名和参数通过通信协议传递给服务端,服务端计算后将返回值同样以通信协议返回,该方法在需要实现分布式的应用系统中较常见。

    复杂的话,可以做成内部总线的形式。

    本文记录一个node.js下thrift的简单例子。

    1、下载thrift编译工具,本人用的是最新的0.92版本(当天),在windows下安装后并配置环境变量;

    2、编写服务定义文件,类似corba里的IDL文件,如下:

      struct User{  
         1: string username,  
         2: string password,    
        }  
        service UserService{  
         void add(1: User u),    
        }  

    3、编译该文件,执行:thrift --gen js:node user.thrift,执行后会在gen-node.js中生成两个文件user_types.js和UserService.js,将两个文件拷贝到需要远程调用的工程中;

    4、在node工程里安装thrift插件包,执行npm install thrift

    5、编写server工程:

    var thrift = require('thrift');
    
    var UserService = require('./gen-nodejs/UserService.js');
    var ttypes = require('./gen-nodejs/user_types');    
    
    
    var users = [];
    
    var server = thrift.createServer(UserService, {
       add: function(user, callback) {
        
        users.push(user);
        console.log("server add:", users);
        callback();
      }
    },{});
    
    server.listen(3344);
    console.log('server start');

    6、编写client工程:

    var thrift = require('thrift');
    
    var UserService = require('./gen-nodejs/UserService.js');
    var ttypes = require('./gen-nodejs/user_types');
    
    var connection = thrift.createConnection('localhost', 3344);
    var  client = thrift.createClient(UserService, connection);
    
    var user = new ttypes.User();
    user.username = 'fredric';
    user.password = "sinny";
    
    connection.on('error', function(err) {
      console.error(err);
    });
    
    client.add(user, function(err, response) {
      if (err) {
        console.error(err);
      } else {
        console.log("client stored:", user.username);
        connection.end();
      }
    });

    7、分别执行server和client工程,会看见client远程调用了server端的add方法。

  • 相关阅读:
    process crashed and the client did not handle it, not reloading the page because we reached the maximum number of attempts
    mac 查看ip
    axios和vue-axios的关系
    export default 和 export 区别
    Mac 编辑hosts文件
    npm --save-dev --save 的区别
    CommonHelper 公共类
    2.06StuModify.aspx(修改姓名,性别,所在班级)
    linux网桥浅析
    Bridge的数据在内核处理流程
  • 原文地址:https://www.cnblogs.com/Fredric-2013/p/4519173.html
Copyright © 2020-2023  润新知