2017-06-02 85 views
0

此時我的REST API工作在PHP上,並且運行在Apache2/Nginx後面(實際上,在Apache2上遷移到Nginx的過程中),但是在閱讀關於Golang和Node.js的性能休息,我正在考慮將我的REST從PHP遷移到這個變體之一,但是我堅持的是如何遷移一些路由,而不是整個REST。將單獨的REST路由從PHP遷移到Node.js/Golang /不管

比如現在我有兩個途徑

/users/articles

Apache是​​偵聽80端口,然後對他們的PHP幫助返回的響應,但如果我要遷移/articles到節點的內容。 JS?如何讓我的網絡服務器知道他需要調用Node.js的/articles如果Node.js將在不同的端口上,但是對於/users仍然使用PHP?

回答

0

發現從我的同事很不錯的解決方案,只是處理請求nginx的和重定向到另一臺服務器,如果請求的URI中包含的東西,如:

server { 
    listen 127.0.0.1:80; 
    server_name localhost.dev; 
    location ~* ^/[a-zA-Z0-9]+_[a-zA-Z0-9]+_(?<image_id>[0-9]+).* { 
     include    proxy_headers.conf; 
     proxy_set_header X-Secure  False; 
     add_header   X-Image-Id $image_id; 
     access_log   off; 
     proxy_pass http://localhost-image-cache; 
     proxy_next_upstream off; 
    } 
} 

upstream localhost-image-cache { 
hash $server_name$image_id consistent; 
    server 127.0.0.1:81 max_fails=0; 
    keepalive 16; 
} 
1

您可以設置新的Node.js REST API以使用舊的PHP REST API,並在準備好時替換Node.js REST API中的端點。

下面是一個使用Hapi.js一個例子(但你可以使用任何Node.js的REST風格的架構):

const Hapi = require('hapi'); 
const request = require('request'); 

const server = new Hapi.Server(); 
server.connection({ port: 81, host: 'localhost' }); 

server.route({ 
    method: 'GET', 
    path: '/new', 
    handler: (req, reply) => { 
     reply('Hello from Node.js API'); 
    } 
}); 

server.route({ 
    method: 'GET', 
    path: '/{endpoint}', 
    handler: (req, reply) => { 
     request.get(`http://localhost:80/${req.params.endpoint}`) 
      .on('response', (response) => { 
      reply(response); 
     }); 
    } 
}); 

server.start((err) => { 
    if (err) { 
     throw err; 
    } 
    console.log(`Server running at: ${server.info.uri}`); 
}); 

您可以在同一臺服務器上同時運行PHP和Node.js的(使用不同的端口),但你可能會更好地在同一個網絡中的不同服務器上運行它們。一旦你移動了所有的端點,你就不會在你的服務器上需要PHP/etc。