Skip to content

Commit 04547fd

Browse files
committed
adding consistent hashing demo
1 parent 50d1902 commit 04547fd

File tree

2 files changed

+70
-2
lines changed

2 files changed

+70
-2
lines changed

demos/consistent-hashing.js

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
// Gateway implementation
2+
3+
'use strict'
4+
5+
const gateway = require('../index')
6+
const ConsistentHash = require('consistent-hash')
7+
8+
const targets = [
9+
'http://localhost:3000',
10+
'http://localhost:3001',
11+
'http://localhost:3002',
12+
]
13+
14+
const consistentHash = new ConsistentHash()
15+
targets.forEach((target) => consistentHash.add(target))
16+
17+
gateway({
18+
routes: [
19+
{
20+
proxyHandler: (req, res, url, proxy, proxyOpts) => {
21+
const target = consistentHash.get(req.path)
22+
proxyOpts.base = target
23+
24+
return proxy(req, res, url, proxyOpts)
25+
},
26+
prefix: '/api',
27+
},
28+
],
29+
})
30+
.start(8080)
31+
.then(() => console.log('API Gateway listening on 8080 port!'))
32+
33+
// Below is the services implementation, commonly located on separated projects
34+
const express = require('express')
35+
36+
// service1.js
37+
const service1 = express()
38+
service1.get('/orders/:orderId', (req, res) => {
39+
res.header('Service-Id', 'service1')
40+
res.send('Order from service 1!')
41+
})
42+
service1.listen(3000, () => {
43+
console.log('Service 1 running!')
44+
})
45+
46+
// service2.js
47+
const service2 = express()
48+
49+
service2.get('/orders/:orderId', (req, res) => {
50+
res.header('Service-Id', 'service2')
51+
res.send('Order from service 2!')
52+
})
53+
54+
service2.listen(3001, () => {
55+
console.log('Service 2 running!')
56+
})
57+
58+
// service3.js
59+
const service3 = express()
60+
61+
service3.get('/orders/:orderId', (req, res) => {
62+
res.header('Service-Id', 'service3')
63+
res.send('Order from service 3!')
64+
})
65+
66+
service3.listen(3002, () => {
67+
console.log('Service 3 running!')
68+
})

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,7 @@
3232
"fast-proxy-lite": "^1.1.2",
3333
"http-cache-middleware": "^1.4.1",
3434
"restana": "^4.9.9",
35-
"stream-to-array": "^2.3.0",
36-
"micromatch": "^4.0.8"
35+
"stream-to-array": "^2.3.0"
3736
},
3837
"files": [
3938
"lib/",
@@ -47,6 +46,7 @@
4746
"artillery": "^2.0.21",
4847
"aws-sdk": "^2.1691.0",
4948
"chai": "^4.5.0",
49+
"consistent-hash": "^1.2.2",
5050
"cors": "^2.8.5",
5151
"express": "^5.0.1",
5252
"express-jwt": "^7.7.8",

0 commit comments

Comments
 (0)