diff --git a/packages/greeter/server.js b/packages/greeter/server.js index 37b8cc7..ac9eab3 100644 --- a/packages/greeter/server.js +++ b/packages/greeter/server.js @@ -2,18 +2,37 @@ import axios from 'axios'; import express from 'express'; import { env, eureka } from '@greeting/shared'; +class SimpleRoundRobin { + constructor(eurekaClient) { + this.eurekaClient = eurekaClient; + this.index = 0; + } + + next() { + const instances = + this.eurekaClient + .getInstancesByAppId('GREETER-MESSAGES') + ?.filter((instance) => instance.status === 'UP') || []; + + if (instances.length === 0) { + return new Error('No instances of GREETER-MESSAGES available'); + } + this.index = this.index % instances.length; + const instance = instances[this.index]; + this.index++; + return instance.hostName; + } +} + const app = express(); const eurekaClient = await eureka.getClient(env.port); - -const lookupService = () => { - return eurekaClient.getInstancesByAppId('GREETER-MESSAGES')[0]?.hostName; -}; +const selector = new SimpleRoundRobin(eurekaClient); app.get('/hello', async (req, res) => { const salutation = req.query.salutation || 'Hello'; const name = req.query.name || 'Bob'; - const url = `https://${lookupService()}/greeting?salutation=${salutation}&name=${name}`; + const url = `https://${selector.next()}/greeting?salutation=${salutation}&name=${name}`; const response = await axios.get(`${url}`, { headers: { diff --git a/packages/shared/src/eureka.js b/packages/shared/src/eureka.js index 0c6dced..a5fab25 100644 --- a/packages/shared/src/eureka.js +++ b/packages/shared/src/eureka.js @@ -25,6 +25,10 @@ const getClient = async (port) => { $: port, '@enabled': true, }, + securePort: { + $: port, + '@enabled': true, + }, vipAddress: 'UNKNOWN', dataCenterInfo: { '@class': 'com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo',