从php迁移到node.js/golang/其他



此时我的REST API在PHP上工作,并且在Apache2/nginx后面运行(在Apache2上实际上,迁移到NGINX正在进行中(,但是在阅读了有关Golang和Node.js的信息之后休息的表现,我正在考虑将其休息从PHP迁移到其中一个变体,但是我坚持的地方是如何迁移一些路线,而不是一一迁移。

例如,现在我有两个路线

/users/articles

Apache正在听80个端口,然后使用PHP帮助返回响应,但是如果我想将/articles迁移到Node.js怎么办?我的Web服务器如何知道/articles如果Node.js在其他端口上,他需要调用Node.js,但对于/users仍使用PHP?

您可以设置新的node.js rest api使用旧的php rest api,并在准备就绪时替换node.js rest API中的端点。

这是使用hapi.js的示例(但是您可以使用任何node.js retful框架(:

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/等。

从我的同事那里找到了一个很好的解决方案,只需使用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;
}

最新更新