eureka-js-client

A JavaScript implementation the Netflix OSS service registry, Eureka.

eureka-js-client

A JavaScript implementation of a client for Eureka (https://github.com/Netflix/eureka), the Netflix OSS service registry.

Usage

First, install the module into your node project:

npm install eureka-js-client --save

Add Eureka client to a Node application.

The Eureka module exports a JavaScript function that can be constructed.

import Eureka from 'eureka-js-client';

// Or, if you're not using a transpiler:
const Eureka = require('eureka-js-client').Eureka;

// example configuration
const client = new Eureka({
  // application instance information
  instance: {
    app: 'jqservice',
    hostName: 'localhost',
    ipAddr: '127.0.0.1',
    port: 8080,
    vipAddress: 'jq.test.something.com',
    dataCenterInfo: {
      name: 'MyOwn',
    },
  },
  eureka: {
    // eureka server host / port
    host: '192.168.99.100',
    port: 32768,
  },
});

The Eureka client searches for the YAML file eureka-client.ymlin the current working directory. It further searches for environment specific overrides in the environment specific YAML files (e.g. eureka-client-test.yml). The environment is typically developmentor production, and is determined by environment variables in this order: EUREKA_ENV, if present, or NODE_ENV, if present. Otherwise it defaults to development. The options passed to the constructor overwrite any values that are set in configuration files.

You can configure a custom directory to load the configuration files from by specifying a cwdoption in the object passed to the Eurekaconstructor.

const client = new Eureka({
  cwd: `${__dirname}/config`,
});

If you wish, you can also overwrite the name of the file that is loaded with the filenameproperty. You can mix the cwdand filenameoptions.

const client = new Eureka({
  filename: 'eureka',
  cwd: `${__dirname}/config`,
});

Register with Eureka & start application heartbeats

client.start();

De-register with Eureka & stop application heartbeats

client.stop();

Get Instances By App ID

const instances = client.getInstancesByAppId('YOURSERVICE');

Get Instances By Vip Address

const instances = client.getInstancesByVipAddress('YOURSERVICEVIP');

Providing Custom Request Middleware

The client exposes the ability to modify the outgoing requestoptions object prior to a eureka call. This is useful when adding authentication methods such as OAuth, or other custom headers. This will be called on every eureka request, so it highly suggested that any long-lived external calls made in the middleware are cached or memoized. If the middleware returns anything other than an object, the eureka request will immediately fail and perform a retry if configured.

// example using middleware to set-up HTTP authentication
const client = new Eureka({
  requestMiddleware: (requestOpts, done) => {
    requestOpts.auth = {
      user: 'username',
      password: 'somepassword'
    };
    done(requestOpts);
  }
});

Configuring for AWS environments

For AWS environments (dataCenterInfo.name == 'Amazon') the client has built-in logic to request the AWS metadata that the Eureka server requires. See Eureka REST schemafor more information.

// example configuration for AWS
const client = new Eureka({
  // application instance information
  instance: {
    app: 'jqservice',
    port: 8080,
    vipAddress: 'jq.test.something.com',
    statusPageUrl: 'http://__HOST__:8080/info',
    healthCheckUrl: 'http://__HOST__:8077/healthcheck',
    homePageUrl: 'http://__HOST__:8080/',
    dataCenterInfo: {
      name: 'Amazon',
    },
  },
  eureka: {
    // eureka server host / port / EC2 region
    host: 'eureka.test.mydomain.com',
    port: 80,
  },
});

Notes:

  • Under this configuration, the instance hostNameand ipAddrwill be set to the public host and public IP that the AWS metadata provides. You can set eureka.useLocalMetadatato trueto use the private host and private IP address instead.
  • If you want to register using the IP address as the hostname, set eureka.preferIpAddressto true. This may be used in combination with eureka.useLocalMetadatafor selecting the private or public IP.
  • For status and healthcheck URLs, you may use the replacement key of __HOST__to use the host from the metadata.
  • Metadata fetching can be disabled by setting config.eureka.fetchMetadatato falseif you want to provide your own metadata in AWS environments.

Looking up Eureka Servers using DNS

If your have multiple availability zones and your DNS entries set up according to the Wiki article Deploying Eureka Servers in EC2, you'll want to set config.eureka.useDnsto trueand set config.eureka.ec2Regionto the current region (usually this can be pulled into your application via an environment variable, or passed in directly at startup).

This will cause the client to perform a DNS lookup using config.eureka.hostand config.eureka.ec2Region. The naming convention for the DNS TXT records required for this to function is also described in the Wiki article above. This feature will also work in non-EC2 environments as long as the DNS records conform to the same convention. The results of the DNS resolution are cached in memory and refreshed every 5 minutes by default (set config.eureka.clusterRefreshIntervalto override).

Zone Affinity

By default, the client will first try to connect to the Eureka server located in the same availability-zone as it's currently in. If availability-zoneis not set in the instance metadata, a random server will be chosen. This also applies when statically configuring the cluster (mapped by zone, see below). To disable this feature, set config.eureka.preferSameZoneto false, and a random server will be chosen.

Statically configuring Eureka server list

While the recommended approach for resolving the Eureka cluster is using DNS (see above), you can also statically configure the list of Eureka servers by zone or just using a simple default list. Make sure to provide the full protocol, host, port, and path to the Eureka REST service (usually /apps/) when using this approach.

Static cluster configuration (map by zone)

// example configuration for AWS (static map of Eureka cluster by availability-zone)
const client = new Eureka({
  instance: {
    ... // application instance information
  },
  eureka: {
    availabilityZones: {
      'us-east-1': ['us-east-1c', 'us-east-1d', 'us-east-1e']
    },
    serviceUrls: {
      'us-east-1c': [
        'http://ec2-fake-552-627-568-165.compute-1.amazonaws.com:7001/eureka/v2/apps/', 'http://ec2-fake-368-101-182-134.compute-1.amazonaws.com:7001/eureka/v2/apps/'
      ],
      'us-east-1d': [...],
      'us-east-1e': [...]
    }
  },
});

Static cluster configuration (list)

// example configuration (static list of Eureka cluster servers)
const client = new Eureka({
  instance: {
    ... // application instance information
  },
  eureka: {
    serviceUrls: {
      default: [
        'http://ec2-fake-552-627-568-165.compute-1.amazonaws.com:7001/eureka/v2/apps/', 'http://ec2-fake-368-101-182-134.compute-1.amazonaws.com:7001/eureka/v2/apps/'
      ]
    }
  },
});

Advanced Configuration Options

optiondefault valuedescription
requestMiddlewarenoopCustom middleware function to modify the outgoing requestto eureka
loggerconsole logginglogger implementation for the client to use
shouldUseDeltafalseExperimental mode to fetch deltas from eureka instead of full registry on update
eureka.maxRetries3Number of times to retry all requests to eureka
eureka.requestRetryDelay500milliseconds to wait between retries. This will be multiplied by the # of failed retries.
eureka.heartbeatInterval30000milliseconds to wait between heartbeats
eureka.registryFetchInterval30000milliseconds to wait between registry fetches
eureka.registerWithEurekatrueenable/disable Eureka registration
eureka.fetchRegistrytrueenable/disable registry fetching
eureka.filterUpInstancestrueenable/disable filtering of instances with status === UP
eureka.servicePath/eureka/v2/apps/path to eureka REST service
eureka.sslfalseenable SSL communication with Eureka server
eureka.useDnsfalselook up Eureka server using DNS, see Looking up Eureka Servers in AWS using DNS
eureka.preferSameZonetrueenable/disable zone affinity when locating a Eureka server
eureka.clusterRefreshInterval300000milliseconds to wait between refreshing cluster hosts (DNS resolution only)
eureka.fetchMetadatatruefetch AWS metadata when in AWS environment, see Configuring for AWS environments
eureka.useLocalMetadatafalseuse local IP and local hostname from metadata when in an AWS environment.
eureka.preferIpAddressfalseuse IP address (local or public) as the hostname for registration when in an AWS environment.

Events

Eureka client is an instance of EventEmitterand provides the following events for consumption:

eventdata provideddescription
startedN/AFired when eureka client is fully registered and all registries have been updated.
registeredN/AFired when the eureka client is registered with eureka.
deregisteredN/AFired when the eureka client is deregistered with eureka.
heartbeatN/AFired when the eureka client has successfully renewed it's lease with eureka.
registryUpdatedN/AFired when the eureka client has successfully update it's registries.

Debugging

The library uses requestfor all service calls, and debugging can be turned on by passing NODE_DEBUG=requestwhen you start node. This allows you you double-check the URL being called as well as other request properties.

NODE_DEBUG=request node example.js

You can also turn on debugging within the library by setting the log level to debug:

client.logger.level('debug');

Known Issues

400 Bad Request Errors from Eureka Server

Later versions of Eureka require a slightly different JSON POST body on registration. If you are seeing 400 errors on registration it's probably an issue with your configuration and it could be the formatting differences below. The history behind this is unclear and there's a discussion here. The main differences are:

  • portis now an object with 2 required fields $and @enabled.
  • dataCenterInfohas an @classproperty.

See below for an example:

const client = new Eureka({
  // application instance information
  instance: {
    app: 'jqservice',
    hostName: 'localhost',
    ipAddr: '127.0.0.1',
    port: {
      '$': 8080,
      '@enabled': true,
    },
    vipAddress: 'jq.test.something.com',
    dataCenterInfo: {
      '@class': 'com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo',
      name: 'MyOwn',
    },
  },
  eureka: {
    // eureka server host / port
    host: '192.168.99.100',
    port: 32768,
  },
});

If you are planning on connecting to a eureka service in AWS you will need to add the corresponding dataCenterInfoinformation:

dataCenterInfo: {
   '@class': 'com.netflix.appinfo.AmazonInfo',
   name: 'Amazon',
  }

404 Not Found Errors from Eureka Server

This probably means that the Eureka REST service is located on a different path in your environment. The default is http://<EUREKA_HOST>/eureka/v2/apps, but depending on your setup you may need to set eureka.servicePathin your configuration to another path. The REST service could be hung under /eureka/apps/or possibly /apps/.

Usage with Spring Cloud

If you are using Spring Cloud you'll likely need the following settings:

  • Set eureka.servicePathin your config to /eureka/apps/.
  • Use the newer style of the configuration hereor Spring Cloud Eureka will throw a 500 error.
  • Set statusPageUrlto a valid URL for your application, Spring Cloud seems to require thiswhen the instance information is parsed.
  • Put single quotes around boolean @enabled. Unfortunately, a 500 error regarding parsing seems to occurwithout that.

Below is an example configuration that should work with Spring Cloud Eureka server:

const client = new Eureka({
  instance: {
    app: 'jqservice',
    hostName: 'localhost',
    ipAddr: '127.0.0.1',
    statusPageUrl: 'http://localhost:8080/info',
    port: {
      '$': 8080,
      '@enabled': 'true',
    },
    vipAddress: 'jq.test.something.com',
    dataCenterInfo: {
      '@class': 'com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo',
      name: 'MyOwn',
    },
  },
  eureka: {
    host: '192.168.99.100',
    port: 32768,
    servicePath: '/eureka/apps/'
  },
});

Tests

The test for the module are written using mocha and chai. To run the unit tests, you can use the gulp testtask:

gulp test

If you wish to have the tests watch the src/and test/directories for changes, you can use the test:watchgulp task:

gulp test:watch

HomePage

https://github.com/jquatier/eureka-js-client

Repository

https://github.com/jquatier/eureka-js-client.git


上一篇:gulp-env
下一篇:qccost-saluki2-node

相关推荐

  • 🙋Hanjst汉吉斯特改进+enSafeExpression安全表达式等

    Hanjst汉吉斯特模版语言及模版引擎,近期持续改进升级。 这次改进主要是增加了对安全输出表达式兼容,由于涉及到对软件开发过程中的效率和软件运行效率的平衡和取舍,所以多写了几句,以描述这个权衡利弊对...

    10 天前
  • 🙋Hanjst汉吉斯特升级:+showImageAsync及性能改进等

    自2019年元旦🙋Hanjst汉吉斯特 模板语言及其编译引擎发布,已经过去一年多了。 这期间随着 🙋Hanjst汉吉斯特 的推广应用,我们也陆续发布了如下一些更新内容: 🛠️Hanjst/汉吉...

    1 个月前
  • 😉我用 Nuxt.js 仿了个掘金

    前言 首先肯定是要夸夸掘金啦,最开始从 CSDN 到 博客园 再到 掘金,个人感觉掘金的技术氛围非常的nice,真是个宝藏社区👏。技术文章大多以前端为主,对前端开发者非常友好,质量也是歪瑞古的。

    21 天前
  • 😀一个原生js弹幕库

    danmujs 😀一个原生js弹幕库,基于 CSS3 Animation 地址、核心代码 本项目基于 rcbullets,项目约70%的代码基于rcbullets,首先要感谢这个项目的作者,如...

    4 个月前
  • 🕵️‍♀️由原型到JS中的“模拟类”

    讲述了有关 JavaScript 中原型相关知识,又引出了 JavaScript 中的“类“究竟是什么?,以及一系列相关问题。 一、前置知识 1、JavaScript 的面向对象(OOP) ​ 面向...

    2 个月前
  • 🔥《吊打面试官》系列 Node.js 必知必会必问!

    (/public/upload/f204a3b224d986128f1b4d9b8d06cd17) 前言 codeing 应当是一生的事业,而不仅仅是 30 岁的青春🍚 本文已收录 Git...

    2 个月前
  • 💖CSS + JS 送学妹满屏幕小爱心

    故事开始 午饭时间,暗恋已久的学妹拉着我的衣袖:“学长学长,你能不能让这些爱心变成五颜六色的吗~”。 我在旁边笑开了花~~~ image.png(/public/upload/04aaa24e...

    1 个月前
  • (vuejs学习)2、使用ElementUI(*)

    1.element安装 开发环境是win10,一到node官网下载node的.msi包(https://npm.taobao.org/mirrors/node/v10.16.0/nodev10.16....

    10 个月前
  • (vuejs学习)1、Vue初上手(*)

    参考《官方(https://cli.vuejs.org/zh/guide/installation.html)》官方: Node 版本要求: Vue CLI 需要 Node.js 8.9 或更高...

    10 个月前
  • 黄金搭档 -- JS 装饰器(Decorator)与Node.js路由

    很多面对象语言中都有装饰器(Decorator)函数的概念,Javascript语言的ES7标准中也提及了Decorator,个人认为装饰器是和一样让人兴奋的的变化。

    1 年前

官方社区

扫码加入 JavaScript 社区