问题描述:

Looking for a good example of how to implement a node API gateway for a microservice application, I understand the purpose of having a gateway, I am just not sure of how to implement this without just adding another level of RESTful route calls. To me a gateway is supposed to just direct the route to the microservice.

API Gateway port 3000

router.use('/microservicename/*', function (req, res, next) {

**code that will direct to microservice**

});

Microservice1 server.js port 3001

var express = require('express');

var app = express();

var routes = require('./routes/routes');

app.use('/microservicename', routes);

var server = app.listen(3001, function () {

console.log('Server running at http://127.0.0.1:3001/');

});

Microservice1 router.js (3001)

router.get('/route1', function (req, res, next) {

//get route code

});

router.post('/route2', function (req, res, next) {

//post route code

});

router.put('/route3', function (req, res, next) {

//put route code

});

router.delete('/route4', function (req, res, next) {

//delete route code

});

网友答案:

Assuming your microservice is its own http server (if not, then please explain more about its architecture) and assuming your API is designed such that you can easily identify which routes go to which microservice without specifying every single possible route, then you should be able to create one route handler for an entire microservice (or at worst a very small number of route handlers for the entire microservice).

For example, if all requests that start with /api/foo go to the foo microservice, then you should be able to have a single route handler that catches /api/foo/* and proxies that to the microservice. If you have common middleware for all requests (such as middleware that runs or verifies an authentication process), that can be in the stack before the proxy route handlers so it will be invoked for all requests that go to the microservice.

If you don't have a 1-to-1 mapping between incoming API calls and microservice APIs, then you have to create a mapping between the two. Depending upon the level of mismatch, you may be able to do this with a table-driven approach where you specify what matches with what in a table and then one piece of generic code processes all the definitions in the table.

相关阅读:
Top