Skip to content

Commit 9f3c4c0

Browse files
committed
Use a simple round robin to select instances
Signed-off-by: kvmw <[email protected]>
1 parent ec44991 commit 9f3c4c0

File tree

2 files changed

+28
-5
lines changed

2 files changed

+28
-5
lines changed

packages/greeter/server.js

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,37 @@ import axios from 'axios';
22
import express from 'express';
33
import { env, eureka } from '@greeting/shared';
44

5+
class SimpleRoundRobin {
6+
constructor(eurekaClient) {
7+
this.eurekaClient = eurekaClient;
8+
this.index = 0;
9+
}
10+
11+
next() {
12+
const instances =
13+
this.eurekaClient
14+
.getInstancesByAppId('GREETER-MESSAGES')
15+
?.filter((instance) => instance.status === 'UP') || [];
16+
17+
if (instances.length === 0) {
18+
return new Error('No instances of GREETER-MESSAGES available');
19+
}
20+
this.index = this.index % instances.length;
21+
const instance = instances[this.index];
22+
this.index++;
23+
return instance.hostName;
24+
}
25+
}
26+
527
const app = express();
628
const eurekaClient = await eureka.getClient(env.port);
7-
8-
const lookupService = () => {
9-
return eurekaClient.getInstancesByAppId('GREETER-MESSAGES')[0]?.hostName;
10-
};
29+
const selector = new SimpleRoundRobin(eurekaClient);
1130

1231
app.get('/hello', async (req, res) => {
1332
const salutation = req.query.salutation || 'Hello';
1433
const name = req.query.name || 'Bob';
1534

16-
const url = `https://${lookupService()}/greeting?salutation=${salutation}&name=${name}`;
35+
const url = `https://${selector.next()}/greeting?salutation=${salutation}&name=${name}`;
1736

1837
const response = await axios.get(`${url}`, {
1938
headers: {

packages/shared/src/eureka.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,10 @@ const getClient = async (port) => {
2525
$: port,
2626
'@enabled': true,
2727
},
28+
securePort: {
29+
$: port,
30+
'@enabled': true,
31+
},
2832
vipAddress: 'UNKNOWN',
2933
dataCenterInfo: {
3034
'@class': 'com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo',

0 commit comments

Comments
 (0)