@@ -2,18 +2,37 @@ import axios from 'axios';
22import express from 'express' ;
33import { 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+
527const app = express ( ) ;
628const 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
1231app . 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 : {
0 commit comments