Skip to content

Commit 7626fb3

Browse files
committed
feat: simple round-robin solution for load-balancing
Signed-off-by: kvmw <[email protected]>
1 parent 232a63a commit 7626fb3

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

packages/greeter/server.js

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@ import { env, eureka } from '@greeting/shared';
44
const app = express();
55
const eurekaClient = await eureka.getClient(env.port);
66

7-
const serviceHost = () => {
7+
// Counter for round-robin load balancing
8+
let instanceCounter = 0;
9+
10+
const getServiceInstance = () => {
811
const instances =
912
eurekaClient
1013
.getInstancesByAppId('GREETER-MESSAGES')
@@ -14,14 +17,17 @@ const serviceHost = () => {
1417
throw new Error('No instances of GREETER-MESSAGES available');
1518
}
1619

17-
return instances[0].hostName;
20+
const selectedInstance = instances[instanceCounter % instances.length];
21+
instanceCounter = (instanceCounter + 1) % instances.length;
22+
23+
return selectedInstance.hostName;
1824
};
1925

2026
app.get('/hello', async (req, res) => {
2127
const salutation = req.query.salutation || 'Hello';
2228
const name = req.query.name || 'Bob';
2329

24-
const url = `https://${serviceHost()}/greeting?salutation=${salutation}&name=${name}`;
30+
const url = `https://${getServiceInstance()}/greeting?salutation=${salutation}&name=${name}`;
2531

2632
const response = await fetch(`${url}`, {
2733
headers: {

0 commit comments

Comments
 (0)