Giter Club home page Giter Club logo

node-ral's Introduction

node-ral

Build Status Coveralls Status NPM version Downloads

node-ral 是一个专为 Node 服务端应用打造的一款工业级后端服务管理库,它的特色是统一了各种通信协议、数据格式的请求接口,提供了集中化的服务资源配置管理能力,以及完善的异常处理和日志记录。

目前 node-ral 已经在百度公司内外经过长时间的使用验证,为多个基于 Node 的产品或框架提供后端服务管理功能,表现非常稳定可靠。

兼容性

  • node 0.10.x
  • node 0.12.x
  • node 4.x
  • node 5.x
  • node 6.x
  • node 8.x

io.js 1.63至1.8.1版本不支持GBK编码

快速开始

node-ral 为了实现后端服务配置的统一管理,要求后端服务请求的配置与业务实现分离,因此在使用之前必须创建后端服务的配置文件。

我们以 百度地图WebAPI 为例做一个简单的DEMO,你也可以直接在example/baidumap中直接下载。

安装
npm init
npm i node-ral --save
创建配置
 // config/ral/API.js 

module.exports.MAPAPI= {           // 声明服务名为MAPAPI
    // 请求协议与数据格式配置
    protocol: 'http',              // 使用http协议请求
    pack: 'querystring',           // 数据封装为query
    unpack: 'json',                // 约定服务端返回JSON数据
    encoding: 'utf-8',             // 服务器返回utf-8编码
    // 负载均衡与超时重试配置
    balance: 'roundrobin',         // 负载均衡策略
    timeout: 500,                  // 请求最长超时时间500ms
    retry: 1,                      // 请求重试次数
    // HTTP协议特有配置
    method: 'GET',                 // 使用GET请求
    query: {                       // 服务的全局query
        ak: '0C62f9f0ee027b6052dfa35b0f38b61a',
        output: 'json',
        page_size: 10,
        page_num: 0,
        scope: 1
    },
    path: '/place/v2/search',      // API路径
    headers: {                     // 服务的全局headers
        'x-client': 'ral'
    },
    // 后端地址配置
    server: [                      // 可以配置多个后端地址
        {
            host: 'api.map.baidu.com',
            port: 80
        }
    ]
}
初始化
// ral.js

var RAL = require('node-ral').RAL;
var ralP = require('node-ral').RALPromise; // 使用Ral的Promise版接口
var path = require('path');

// 初始化RAL,只需在程序入口运行一次
RAL.init({
    // 指定RAL配置目录
    confDir: path.join(__dirname, 'config/ral')
});

module.exports = ralP;
调用服务
// index.js

var ralP = require('./ral.js');
var assert = require('assert');

ralP('MAPAPI', {
    data: {
        region: '北京',
        query: '奥林匹克森林公园'
    }
}).then(function (data) {
    assert.equal(data.status, 0);
    console.dir(data.results[0]);
}).catch(function (err) {
    console.error(err);
});
执行结果

执行一下 node index.js 我们就可以看到奥林匹克森林公园的搜索结果了

 {
     name: '奥林匹克森林公园',
     location: { lat: 40.025255, lng: 116.396803 },
     address: '北京市朝阳区安立路',
     street_id: '03d7e5971f3675483c9a5e9e',
     telephone: '010-64529060',
     uid: '03d7e5971f3675483c9a5e9e'
 } 

同时我们可以在 logs 目录查看请求的具体日志

比如 HTTP 协议请求日志,在这里我们可以看到由协议提供的一些日志信息

TRACE: 15-04-28 17:07:45 [-:-] errno[-] logId[-] uri[-] user[-] refer[-] cookie[-]  [yog-ral] [cluster main][HttpProtocol] request start {"host":"api.map.baidu.com","port":80,"path":"/place/v2/search?ak=0C62f9f0ee027b6052dfa35b0f38b61a&output=json&page_size=10&page_num=0&scope=1&region=%E5%8C%97%E4%BA%AC&query=%E5%A5%A5%E6%9E%97%E5%8C%B9%E5%85%8B%E6%A3%AE%E6%9E%97%E5%85%AC%E5%9B%AD","method":"GET","headers":{"x-client":"ral"},"agent":false} 

以及 node-ral 通用的日志信息,其中会包括服务的基本信息以及各个阶段的处理时间

NOTICE: 15-04-28 17:07:45 [-:-] errno[-] logId[-] uri[-] user[-] refer[-] cookie[-]  [yog-ral] [cluster main][RAL] request end service=MAPAPI requestID=22268922 conv=querystring/json prot=http method=GET path=/place/v2/search remote=api.map.baidu.com:80 cost=116.579 talk=115.316 write=108.190 read=3.633 pack=0.744 unpack=1.056 retry=0/1 

文档

请查阅文档WIKI

node-ral's People

Contributors

andycall avatar greenkeeperio-bot avatar hefangshi avatar nwind avatar portrayer avatar ssddi456 avatar xtx1130 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-ral's Issues

请问有baseURL的功能么

由于测试接口与实际接口URL不是完全一致 上线需要修改多个请求path 请问ral有baseURL功能么?

这个框架的规划是什么

这个框架是不是要做成服务总线一样的框架,如Java世界的dubbo,还是如Uber tchannel一样,微服务的服务管理与服务治理框架?f

动态加载配置

你好:

我希望能动态的注册服务,而不是从配置文件中加载他们;

所以我在初始化的时候配置了一个空目录:

// 初始化RAL
RAL.init({
  confDir: path.join(process.cwd(), 'api/empty')
});

接着在代码里通过Config.loadRawConf方法加载服务的配置对象
但是这个时候lib/config.js#L232中的contextCache[serviceID] 为undefined
我想大概是因为缓存是在load方法中注册的吧

我想在这行代码前面加上下面的代码, 用来确保缓存缓存被正常初始化;

if (!contextCache[serviceID]) {
  contextCache[serviceID] = {};
}

可以提个pr吗?

httpProtocolBase 数据问题

0.11.x中有对 data处理的修改,当数据量比较多的时候,导致http请求服务获取数据不完整,
0.9.x版本是可以,
不清楚是什么问题导致的,麻烦能否看下
个人猜测240行, chunk如果是片段导致
···
ResponseStream.prototype.write = function(chunk) {
// store the data
this.chunks.push(chunk);
this.emit('data', chunk);
};

···

Throw exist error when running in cluster mode.

fs.mkdirSync(this.tmpPath);

{ Error: EEXIST: file already exists, mkdir '/home/work/orp/node_modules/yog2-kernel/node_modules/node-ral/tmp'
at Error (native)
at Object.fs.mkdirSync (fs.js:916:18)
at new Updater (/home/work/orp/node_modules/yog2-kernel/node_modules/node-ral/lib/config/configUpdater.js:36:12)
at Object. (/home/work/orp/node_modules/yog2-kernel/node_modules/node-ral/lib/config/configUpdater.js:163:15)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.require (module.js:468:17)
errno: -17,
code: 'EEXIST',
syscall: 'mkdir',
path: '/home/work/orp/node_modules/yog2-kernel/node_modules/node-ral/tmp' }

什么时候能支持Node.js 7.2.1?

Node.js 7.2.1环境下,总是报这样的问题:

TypeError: The header content contains invalid characters
at ClientRequest.setHeader (_http_outgoing.js:362:11)
at new ClientRequest (_http_client.js:85:14)\n at Object.request (http.js:26:10)

httpProtocolBase retry

初次请求get path = /index,query={k:value}
会转换成
path=/index?k=value;

然后 有个操作

    config.path = path;

当请求retry的时候 path=/index?k=value,query={k:value}
在转换 path=path=/index?k=value&k=value

 if (query) {
        // didn't handle # situation since backend should not get a hash tag
        if (config.path.indexOf('?') === -1) {
            path = config.path + '?' + query;
        }
        else {
            path = config.path + '&' + query;
        }
    }
    else {
        path = config.path;
    }

后面的query会不断的累加,麻烦能否看下解决下

ralP

ralP('API', {
data: {
		limit: 3,
		page: 1,
    }
}).then(function (data) {
    // assert.equal(data.status, 0);
    console.dir(data);
}).catch(function (err) {
    console.error(err);
});

:Error: Invalid service name : API

这个错误该如何解决呀

post请求

用ral配置的post请求一直报403错,一直没找到问题,怀疑是配置有问题。可否给个请求post的配置

以下是我的配置:

module.exports.CNODEPOST= { // 声明服务名为CNODEPOST
// 请求协议与数据格式配置
protocol: 'http', // 使用http协议请求
pack: 'form', // 数据封装为form
unpack: 'json', // 约定服务端返回JSON数据
encoding: 'utf-8', // 服务器返回utf-8编码
balance: 'roundrobin', // 负载均衡策略
timeout: 500, // 请求最长超时时间500ms
retry: 1, // 请求重试次数
method: 'POST', // 使用POST请求
headers: { // 服务的全局headers
'Content-Type':'application/x-www-form-urlencoded',
'x-client-name': 'ral'
},
// 后端地址配置
server: [ // 可以配置多个后端地址
{
host: 'cnodejs.org',
port: 80
}
]
}

request query merge issue

每次请求的service的config merge貌似有问题,复现分三步

  1. 第一次请求
{"pageSize":"20","pageNo":"1","catId":"5000009","catLevel":"3"}
  1. 第二次请求
{"pageSize":"20","pageNo":"1","keyword":"TOTO"}
  1. 第三次请求
{"pageSize":"20","pageNo":"1","catId":"5000009","catLevel":"3"}

问题出现了

第三步的实际请求参数是

query:
   { pageSize: '20',
     pageNo: '1',
     keyword: 'TOTO',
     catId: '5000009',
     catLevel: '3' }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.