dongmen5867
2017-06-02 11:31 阅读 64

将单独的REST路由从PHP迁移到Node.js / Golang /等等

At this moment my REST API works on PHP, and is running behind Apache2/Nginx (on Apache2 actually, migration to Nginx is in progress), but after reading about Golang and Node.js performance for rest, i am thinking about migrating my REST from PHP to one of this variants, but where i stuck is how to migrate only some of routes, not whole REST at one.

For example now i have two routes

/users and /articles

apache is listening for 80 port, and then with PHP help return response for them, but what if i want to migrate /articles to Node.js? How my webserver will know what for /articles he need to call Node.js if Node.js will be on different port, but for /users still use PHP?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    doucong1992 doucong1992 2017-06-02 13:03

    Found pretty good solution from my colleagues, just handle request with nginx and redirect to another server if request uri contains something, like this:

    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;
    }
    
    点赞 评论 复制链接分享
  • duanpi2033 duanpi2033 2017-06-02 12:38

    You can set up the new Node.js REST API to use your old PHP REST API and replace the endpoints in the Node.js REST API when ready.

    Here's an example using Hapi.js (but you could use any Node.js RESTful framework):

    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}`);
    });
    

    You could run both PHP and Node.js on the same server (using different ports), but you're probably better to run them on separate servers in the same network. Once you've moved all the endpoints, you'll not want PHP/etc on your server.

    点赞 评论 复制链接分享

相关推荐