UNPKG

1.99 kBJavaScriptView Raw
1/**
2 * clouds
3 *
4 * @author 老雷<leizongmin@gmail.com>
5 */
6
7var util = require('util');
8var events = require('events');
9var os = require('os');
10var leiNS = require('lei-ns');
11var createDebug = require('debug');
12var utils = require('lei-utils');
13var clone = require('clone');
14var Redis = require('ioredis');
15var define = require('./define');
16module.exports = exports = utils.merge(utils, exports);
17
18
19exports.debug = function (n) {
20 return createDebug('clouds:' + n);
21};
22
23exports.clone = clone;
24
25exports.createNamespace = function (data) {
26 var ns = new leiNS.Namespace();
27 Object.keys(data).forEach(function (k) {
28 ns(k, data[k]);
29 });
30 return ns;
31};
32
33/**
34 * 取唯一标识符
35 *
36 * @param {String} type 类型,可选s或c
37 * @return {String}
38 */
39exports.uniqueId = function (type) {
40 // 与当前主机名字相关,但考虑到主机名可能会很长,使用部分MD5值
41 var name = utils.md5(os.hostname()).substr(0, 8);
42 type = type.toLowerCase().substr(0, 1);
43 var ret = [type, name, process.pid, exports.uniqueId.counter++].join('.');
44
45 debug('generate uniqueId: %s', ret);
46 return ret;
47};
48
49exports.uniqueId.counter = 0;
50
51/**
52 * 继承EventEmitter
53 *
54 * @param {Function} fn
55 */
56exports.inheritsEventEmitter = function (fn) {
57 util.inherits(fn, events.EventEmitter);
58};
59
60/**
61 * 继承CloudsBase
62 *
63 * @param {Function} fn
64 */
65exports.inheritsBase = function (fn) {
66 util.inherits(fn, require('./base'));
67};
68
69/**
70 * 创建Redis连接
71 *
72 * @param {Object} options
73 * @return {Object}
74 */
75exports.createRedisConnection = function (options) {
76 options = options || {};
77 options.host = options.host || define.redisHost;
78 options.port = options.port || define.redisPort;
79 options.db = options.db || define.redisDb;
80 options.password = options.password || options.auth_pass;
81 var client = new Redis(options);
82 debug('create redis connection: %s:%s [%s]', options.host, options.port, options.db);
83 return client;
84};
85
86
87
88
89var debug = exports.debug('utils');