Skip to content

Instantly share code, notes, and snippets.

View JacksonTian's full-sized avatar
🚗
Working on Darabonba.

Jackson Tian JacksonTian

🚗
Working on Darabonba.
View GitHub Profile
var cluster = require('cluster');
var PORT = +process.env.PORT || 1337;
if (cluster.isMaster) {
// In real life, you'd probably use more than just 2 workers,
// and perhaps not put the master and worker in the same file.
cluster.fork();
cluster.fork();
cluster.on('disconnect', function(worker) {
anonymous
anonymous / apimergecall.js
Created December 24, 2012 07:49
API内部有两个http接口A,B并发调用,如果都在200ms内返回,则合并结果输出,如果B比A慢,且B耗时超过200ms,则丢弃B调用只返回A结果.
function apiMergeCall(apis, mainid, timeout, callback){
var api_count = apis.length, ready_count = 0, rst = {}, is_ret = false, start_time = new Date().getTime(),
doCallback = function(){
if (!is_ret && (is_ret = true)) {
timer && clearTimeout(timer);
callback(rst);
}
},
chkResult = function(id, ret){
rst[id] = ret;
@JacksonTian
JacksonTian / api.js
Last active June 28, 2016 01:40
Go语言的actor并发模式更容易,一点都不绕,比如要实现一个API,API内部有两个http接口A,B并发调用,如果都在200ms内返回,则合并结果输出,如果B比A慢,且B耗时超过200ms,则丢弃B调用只返回A结果;用Go很容易实现这个逻辑,50行 - 牛,学到了,但看逻辑是不是A和B如果都超过200ms了就无结果输出?这种情况下需要等A返回了再返回 - 逻辑还可以再完善一下,如果ab都在200ms内返回应该在慢的那个返回时就触发,而不是等到200ms - 接着上面的需求,如果B之后还要根据B的结果来判断是否要调用C,然后B和C的结果和A join后再进入下一个阶段 用我自己的EventProxy库做了下重构 https://gist.github.com/4364823 加注释50行。
var callA = function (callback) {
setTimeout(function () {
callback({name: "a", data: "I am result A"});
}, Math.round(Math.random() * 300));
};
var callB = function (callback) {
setTimeout(function () {
callback({name: "b", data: Math.round(Math.random() * 300)) % 2 === 0});
}, Math.round(Math.random() * 300));
@shokai
shokai / mongoose_virtual_attr.js
Created August 1, 2012 17:32
mongoose virtual attributes
// http://mongoosejs.com/docs/virtuals.html
// npm install mongoose underscore
var _ = require('underscore');
var mongoose = require('mongoose');
mongoose.connect(process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://localhost/test', function(err){
if(err){
console.error(err);
process.exit(1);
@JacksonTian
JacksonTian / avoid_duplicate_call.js
Created January 16, 2012 04:00
避免重复调用,从容应对雪崩问题
var emitter = new event.Emitter();
var status = "ready";
var select = function (callback) {
emitter.once("selected", function (results) {
callback(results);
});
if (status === "ready") {
status = "pending";
db.select("SQL", function (results) {
@pgriess
pgriess / sendfile.js
Created September 16, 2010 20:53
Using sendfile(2) with NodeJS
var assert = require('assert');
var net = require('net');
var open = process.binding('fs').open;
var sendfile = process.binding('fs').sendfile;
if (process.argv.length < 4) {
console.error('usage: sendfile <port> <path>');
process.exit(1);
}