### Run Example Client from Distribution Source: https://github.com/netflix/eureka/blob/master/eureka-examples/README.md Starts the example Eureka client from the built distribution to discover and interact with registered services. ```bash ./bin/ExampleEurekaClient ``` -------------------------------- ### Run Example Service from Distribution Source: https://github.com/netflix/eureka/blob/master/eureka-examples/README.md Starts the example Eureka service from the built distribution. Ensure it registers with Eureka by looking for the readiness message. ```bash ./bin/ExampleEurekaService ``` -------------------------------- ### Run Example Client with Gradle Source: https://github.com/netflix/eureka/blob/master/eureka-examples/README.md Executes the example client using Gradle to discover and communicate with the example service via Eureka. ```bash ./gradlew :eureka-examples:runExampleClient ``` -------------------------------- ### Run Governated Example Service from Distribution Source: https://github.com/netflix/eureka/blob/master/eureka-examples/README.md Starts the governated example Eureka service from the built distribution. This version uses Governator/Guice for initialization. ```bash ./bin/ExampleEurekaGovernatedService ``` -------------------------------- ### Run Governated Example Service with Gradle Source: https://github.com/netflix/eureka/blob/master/eureka-examples/README.md Executes the governated example service using Gradle. This version utilizes Governator/Guice for initialization. ```bash ./gradlew :eureka-examples:runExampleGovernatedService ``` -------------------------------- ### Run Example Service with Gradle Source: https://github.com/netflix/eureka/blob/master/eureka-examples/README.md Executes the example service using Gradle. Wait for the confirmation message indicating successful registration with Eureka. ```bash ./gradlew :eureka-examples:runExampleService ``` -------------------------------- ### Build Eureka Examples Distribution Zip Source: https://github.com/netflix/eureka/blob/master/eureka-examples/README.md Creates a zip distribution of the Eureka examples using Gradle, which can then be used to run the service and client. ```bash ./gradlew :eureka-examples:distZip ``` -------------------------------- ### Register Service with Eureka (Non-AWS) Source: https://context7.com/netflix/eureka/llms.txt Initialize ApplicationInfoManager and DiscoveryClient to register a service instance. The instance starts as STARTING, allowing initialization before becoming UP and ready to serve traffic. Ensure clean shutdown by calling eurekaClient.shutdown(). ```java import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.MyDataCenterInstanceConfig; import com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider; import com.netflix.discovery.DefaultEurekaClientConfig; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.EurekaClient; public class MyService { private static ApplicationInfoManager applicationInfoManager; private static EurekaClient eurekaClient; public static void main(String[] args) throws InterruptedException { // 1. Build InstanceInfo from eureka-client.properties on the classpath MyDataCenterInstanceConfig instanceConfig = new MyDataCenterInstanceConfig(); InstanceInfo instanceInfo = new EurekaConfigBasedInstanceInfoProvider(instanceConfig).get(); applicationInfoManager = new ApplicationInfoManager(instanceConfig, instanceInfo); // 2. Create the DiscoveryClient (registers with Eureka, starts heartbeats) eurekaClient = new DiscoveryClient(applicationInfoManager, new DefaultEurekaClientConfig()); // 3. Signal STARTING while doing app-specific init applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.STARTING); Thread.sleep(2000); // simulate initialization // 4. Mark as UP — Eureka will now route traffic here applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.UP); System.out.println("Service registered and UP. Serving traffic..."); // 5. On shutdown, deregister cleanly Runtime.getRuntime().addShutdownHook(new Thread(() -> { System.out.println("Shutting down — deregistering from Eureka"); eurekaClient.shutdown(); })); } } ``` -------------------------------- ### Eureka Server Deployment and JVM Flags Source: https://context7.com/netflix/eureka/llms.txt Deploy the Eureka server WAR and pass JVM flags for fast local development setup. ```bash # Deploy the Eureka server WAR (after building with ./gradlew clean build) cp ./eureka-server/build/libs/eureka-server-*.war $TOMCAT_HOME/webapps/eureka.war # Pass JVM flags at startup for fast local dev setup export JAVA_OPTS="-Deureka.waitTimeInMsWhenSyncEmpty=0 -Deureka.numberRegistrySyncRetries=0" $TOMCAT_HOME/bin/startup.sh # Access the Eureka dashboard open http://localhost:8080/eureka ``` -------------------------------- ### Discovering a Service with Round-Robin Load Balancing Source: https://context7.com/netflix/eureka/llms.txt Use EurekaClient.getNextServerFromEureka to get a server for basic round-robin load balancing across UP instances for a given VIP address. ```java import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.EurekaClient; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; public class MyClient { private final EurekaClient eurekaClient; public MyClient(EurekaClient eurekaClient) { this.eurekaClient = eurekaClient; } public void callBackendService() { // VIP address matches 'eureka.vipAddress' in the service's properties file String vipAddress = "sampleservice.mydomain.net"; InstanceInfo server; try { server = eurekaClient.getNextServerFromEureka(vipAddress, false /* not secure */); } catch (RuntimeException e) { System.err.println("No instances available for VIP: " + vipAddress); return; } System.out.printf("Connecting to %s:%d (status=%s)%n", server.getHostName(), server.getPort(), server.getStatus()); try (Socket socket = new Socket()) { socket.connect(new InetSocketAddress(server.getHostName(), server.getPort()), 3000); System.out.println("Connected successfully"); // ... send/receive data ... } catch (IOException e) { System.err.println("Connection failed: " + e.getMessage()); // Retry with next server from Eureka on failure } } } ``` -------------------------------- ### Get Next Server from Eureka for Load Balancing Source: https://github.com/netflix/eureka/wiki/Understanding-eureka-client-server-communication Retrieve the next available server instance for a given VIP address from Eureka for client-side load balancing. Handles basic connection attempts. ```java InstanceInfo nextServerInfo = DiscoveryManager.getInstance() .getDiscoveryClient() .getNextServerFromEureka(vipAddress, false); Socket s = new Socket(); int serverPort = nextServerInfo.getPort(); try { s.connect(new InetSocketAddress(nextServerInfo.getHostName(), serverPort)); } catch (IOException e) { System.err.println("Could not connect to the server :" + nextServerInfo.getHostName() + " at port " + serverPort); } ``` -------------------------------- ### Build and Run Eureka Write Server Source: https://github.com/netflix/eureka/wiki/Eureka-2.0-Server-Configuration-And-Use Provides commands to clone the Eureka repository, checkout the 2.x branch, navigate to the write server directory, and run the server using Gradle. ```bash git clone https://github.com/Netflix/eureka.git cd eureka/ git checkout 2.x cd eureka2-write-server/ ../gradlew run ``` -------------------------------- ### Build Eureka Server Source: https://github.com/netflix/eureka/wiki/Building-Eureka-Client-and-Server Navigate to the Eureka directory and execute the Gradle build command to compile the server and client. ```sh cd eureka ./gradlew clean build ``` -------------------------------- ### Initialize DiscoveryClient with CloudInstanceConfig Source: https://github.com/netflix/eureka/wiki/Integrating-Eureka-and-Asgard For Java API clients, initialize DiscoveryClient with CloudInstanceConfig to configure the Eureka client for the Amazon datacenter, enabling Asgard integration. ```java DiscoveryManager.getInstance().initComponent( new CloudInstanceConfig(), new DefaultEurekaClientConfig()); ``` -------------------------------- ### Query All Instances of an Application Source: https://context7.com/netflix/eureka/llms.txt Retrieve all registered instances for a specific application. This is useful for non-Java clients implementing their own service discovery. You can query by application ID, specific instance ID, VIP address, or all applications. ```bash # Get all instances of MY-SERVICE curl -X GET \ http://eureka-server:8761/eureka/v2/apps/MY-SERVICE \ -H 'Accept: application/json' \ -H 'Accept-Encoding: gzip' \ --compressed # Response: JSON with all instances and their status, IP, port, metadata # Get a specific instance curl -X GET \ http://eureka-server:8761/eureka/v2/apps/MY-SERVICE/myhost.example.com \ -H 'Accept: application/json' # Get all applications in the registry curl -X GET \ http://eureka-server:8761/eureka/v2/apps \ -H 'Accept: application/json' # Query by VIP address curl -X GET \ http://eureka-server:8761/eureka/v2/vips/myservice.internal.net \ -H 'Accept: application/json' # Query by instance ID directly curl -X GET \ http://eureka-server:8761/eureka/v2/instances/myhost.example.com \ -H 'Accept: application/json' ``` -------------------------------- ### Build and Run Eureka Read Server Source: https://github.com/netflix/eureka/wiki/Eureka-2.0-Server-Configuration-And-Use Provides commands to clone the Eureka repository, checkout the 2.x branch, navigate to the read server directory, and run the server using Gradle. ```bash git clone https://github.com/Netflix/eureka.git cd eureka/ git checkout 2.x cd eureka2-read-server/ ../gradlew run ``` -------------------------------- ### Configure Tomcat for Fast Eureka Server Startup Source: https://github.com/netflix/eureka/blob/master/eureka-examples/README.md Sets Java options in Tomcat's setenv.sh to speed up the Eureka demo server startup by disabling safeguards. These options are documented in EurekaServerConfig.java. ```bash JAVA_OPTS=" \ -Deureka.waitTimeInMsWhenSyncEmpty=0 \ -Deureka.numberRegistrySyncRetries=0" ``` -------------------------------- ### Initialize Eureka Client (Pre 1.1.153) Source: https://github.com/netflix/eureka/wiki/Understanding-eureka-client-server-communication Initialize the Eureka Client using CloudInstanceConfig for AWS environments. This method is for versions prior to 1.1.153. ```java DiscoveryManager.getInstance().initComponent( new CloudInstanceConfig(), new DefaultEurekaClientConfig()); ``` -------------------------------- ### Query All Instances of an Application Source: https://context7.com/netflix/eureka/llms.txt Retrieve all registered instances for a specific application, useful for non-Java clients implementing their own service discovery. ```APIDOC ## GET /eureka/v2/apps/{appId} ### Description Retrieve all registered instances for a specific application. ### Method GET ### Endpoint /eureka/v2/apps/{appId} ### Parameters #### Path Parameters - **appId** (string) - Required - The ID of the application. ### Response #### Success Response (200) JSON containing all instances and their status, IP, port, and metadata. ### Request Example ```bash curl -X GET \ http://eureka-server:8761/eureka/v2/apps/MY-SERVICE \ -H 'Accept: application/json' \ -H 'Accept-Encoding: gzip' \ --compressed ``` ``` ```APIDOC ## GET /eureka/v2/apps/{appId}/{instanceId} ### Description Retrieve a specific instance of an application. ### Method GET ### Endpoint /eureka/v2/apps/{appId}/{instanceId} ### Parameters #### Path Parameters - **appId** (string) - Required - The ID of the application. - **instanceId** (string) - Required - The ID of the instance. ### Response #### Success Response (200) JSON object representing the specific instance. ### Request Example ```bash curl -X GET \ http://eureka-server:8761/eureka/v2/apps/MY-SERVICE/myhost.example.com \ -H 'Accept: application/json' ``` ``` ```APIDOC ## GET /eureka/v2/apps ### Description Retrieve all applications registered in the registry. ### Method GET ### Endpoint /eureka/v2/apps ### Response #### Success Response (200) JSON object containing all registered applications. ### Request Example ```bash curl -X GET \ http://eureka-server:8761/eureka/v2/apps \ -H 'Accept: application/json' ``` ``` ```APIDOC ## GET /eureka/v2/vips/{vipAddress} ### Description Query applications by VIP address. ### Method GET ### Endpoint /eureka/v2/vips/{vipAddress} ### Parameters #### Path Parameters - **vipAddress** (string) - Required - The VIP address to query. ### Response #### Success Response (200) JSON object containing applications associated with the VIP address. ### Request Example ```bash curl -X GET \ http://eureka-server:8761/eureka/v2/vips/myservice.internal.net \ -H 'Accept: application/json' ``` ``` ```APIDOC ## GET /eureka/v2/instances/{instanceId} ### Description Query an instance directly by its instance ID. ### Method GET ### Endpoint /eureka/v2/instances/{instanceId} ### Parameters #### Path Parameters - **instanceId** (string) - Required - The ID of the instance. ### Response #### Success Response (200) JSON object representing the specific instance. ### Request Example ```bash curl -X GET \ http://eureka-server:8761/eureka/v2/instances/myhost.example.com \ -H 'Accept: application/json' ``` ``` -------------------------------- ### Initialize Eureka Client (Other Data Centers) Source: https://github.com/netflix/eureka/wiki/Understanding-eureka-client-server-communication Initialize the Eureka Client using MyDataCenterInstanceConfig for non-AWS data centers. This method is for versions prior to 1.1.153. ```java DiscoveryManager.getInstance().initComponent( new MyDataCenterInstanceConfig(), new DefaultEurekaClientConfig()); ``` -------------------------------- ### Dependency Injection with Guice/Governator (EurekaModule) Source: https://context7.com/netflix/eureka/llms.txt Initialize Eureka client using Netflix Governator and Guice for dependency injection. This approach automatically manages lifecycle hooks and is recommended for production services. ```java import com.google.inject.AbstractModule; import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.appinfo.MyDataCenterInstanceConfig; import com.netflix.config.DynamicPropertyFactory; import com.netflix.discovery.guice.EurekaModule; import com.netflix.governator.InjectorBuilder; import com.netflix.governator.LifecycleInjector; public class GovernatedServiceMain { public static void main(String[] args) throws Exception { LifecycleInjector injector = InjectorBuilder .fromModules( new EurekaModule(), // provides EurekaClient, ApplicationInfoManager new MyApplicationModule() // your service bindings ) .overrideWith(new AbstractModule() { @Override protected void configure() { DynamicPropertyFactory config = DynamicPropertyFactory.getInstance(); bind(DynamicPropertyFactory.class).toInstance(config); // Override default CloudInstanceConfig with non-AWS config bind(EurekaInstanceConfig.class).to(MyDataCenterInstanceConfig.class); } }) .createInjector(); // Blocks until injector.shutdown() is called or JVM exits injector.awaitTermination(); injector.shutdown(); } static class MyApplicationModule extends AbstractModule { @Override protected void configure() { bind(MyService.class).asEagerSingleton(); // @PostConstruct/@PreDestroy managed by Governator } } } ``` -------------------------------- ### Build Eureka Registration Client Source: https://github.com/netflix/eureka/wiki/Eureka-2.0-Client-Configuration-And-Use Construct an instance of the EurekaRegistrationClient using its builder. Requires a server resolver to be provided. ```java EurekaRegistrationClient registrationClient = new EurekaRegistrationClientBuilder() .withServerResolver(myResolver) .build(); ``` -------------------------------- ### Renew Instance Lease (Heartbeat) Source: https://context7.com/netflix/eureka/llms.txt Send a heartbeat to keep an instance registration alive. If the server does not receive a heartbeat for 90 seconds, it will evict the instance. The loop automatically re-registers if the instance is not found. ```bash # Renew lease — PUT /eureka/v2/apps/{appId}/{instanceId} curl -X PUT \ http://eureka-server:8761/eureka/v2/apps/MY-SERVICE/myhost.example.com \ -H 'Content-Type: application/json' # Response: 200 OK (success), 404 (not registered — must re-register) # Shell loop to send heartbeats every 30 seconds while true; do STATUS=$(curl -s -o /dev/null -w "%{http_code}" -X PUT \ http://eureka-server:8761/eureka/v2/apps/MY-SERVICE/myhost.example.com) if [ "$STATUS" = "404" ]; then echo "Instance not found — re-registering" # call registration curl here fi sleep 30 done ``` -------------------------------- ### Registering an Instance with Eureka Client Source: https://github.com/netflix/eureka/wiki/Eureka-2.0-Client-Configuration-And-Use Initiates the registration of an instance with the Eureka server. Subscription to the returned observable triggers the registration process. The initialRegistrationResult observable emits when the first registration is successful. ```java Observable staticInstanceInfo = Observable.just(myInstanceInfo); RegistrationObservable registrationObservable = registrationClient.register(staticInstanceInfo); registrationObservable.subscribe(); registrationObservable.initialRegistrationResult().doOnCompleted(new Action0() { @Override public void call() { System.out.println("Initial registration completed"); } }).subscribe(); ``` -------------------------------- ### Build Eureka Interest Client Source: https://github.com/netflix/eureka/wiki/Eureka-2.0-Client-Configuration-And-Use Instantiate an EurekaInterestClient using its builder pattern. A ServerResolver must be provided to specify the remote Eureka server. ```java EurekaInterestClient registrationClient = new EurekaInterestClientBuilder() .withServerResolver(myResolver) .build(); ``` -------------------------------- ### Manage Instance Status and Deregistration Source: https://context7.com/netflix/eureka/llms.txt Control the lifecycle of an instance by overriding its status or deregistering it from the registry. Use 'OUT_OF_SERVICE' to prevent traffic, 'UP' to restore, and DELETE to deregister. ```bash # Take instance OUT_OF_SERVICE (e.g., before deployment) curl -X PUT \ "http://eureka-server:8761/eureka/v2/apps/MY-SERVICE/myhost.example.com/status?value=OUT_OF_SERVICE" # Response: 200 OK (success), 500 (failure) # Restore instance to UP (remove status override) curl -X DELETE \ "http://eureka-server:8761/eureka/v2/apps/MY-SERVICE/myhost.example.com/status?value=UP" # Response: 200 OK (success), 500 (failure) # Add/update metadata key-value pair curl -X PUT \ "http://eureka-server:8761/eureka/v2/apps/MY-SERVICE/myhost.example.com/metadata?deployedAt=2024-01-15T10:00:00Z" # Response: 200 OK # Deregister (cancel) instance curl -X DELETE \ http://eureka-server:8761/eureka/v2/apps/MY-SERVICE/myhost.example.com # Response: 200 OK (success), 500 (failure) ``` -------------------------------- ### Querying UP Instances by VIP Address Source: https://context7.com/netflix/eureka/llms.txt Retrieve all UP instances for a VIP address to implement custom load balancing, health filtering, or weighted routing logic. ```java import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.EurekaClient; import java.util.List; import java.util.stream.Collectors; public class ServiceLocator { private final EurekaClient eurekaClient; public ServiceLocator(EurekaClient eurekaClient) { this.eurekaClient = eurekaClient; } public List getUpEndpoints(String vipAddress) { List instances = eurekaClient.getInstancesByVipAddress(vipAddress, false); return instances.stream() .filter(i -> InstanceInfo.InstanceStatus.UP == i.getStatus()) .map(i -> "http://" + i.getHostName() + ":" + i.getPort()) .collect(Collectors.toList()); } public static void main(String[] args) { // Assume eurekaClient is already initialized EurekaClient client = /* initializeEurekaClient() */ null; ServiceLocator locator = new ServiceLocator(client); List endpoints = locator.getUpEndpoints("sampleservice.mydomain.net"); System.out.println("Available endpoints: " + endpoints); // Output: Available endpoints: [http://host1.example.com:8001, http://host2.example.com:8001] } } ``` -------------------------------- ### Registering a Service in AWS Cloud with Eureka Source: https://context7.com/netflix/eureka/llms.txt Use CloudInstanceConfig and pass -Deureka.datacenter=cloud to automatically populate EC2 instance metadata for service registration. ```java import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.CloudInstanceConfig; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider; import com.netflix.discovery.DefaultEurekaClientConfig; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.EurekaClient; // Run with: java -Deureka.datacenter=cloud -jar myservice.jar public class MyAwsService { public static void main(String[] args) { // CloudInstanceConfig reads EC2 metadata from http://169.254.169.254/latest/metadata CloudInstanceConfig instanceConfig = new CloudInstanceConfig(); InstanceInfo instanceInfo = new EurekaConfigBasedInstanceInfoProvider(instanceConfig).get(); ApplicationInfoManager appInfoManager = new ApplicationInfoManager(instanceConfig, instanceInfo); EurekaClient eurekaClient = new DiscoveryClient(appInfoManager, new DefaultEurekaClientConfig()); appInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.UP); System.out.println("Registered in zone: " + instanceConfig.getMetadataMap().get("availability-zone")); Runtime.getRuntime().addShutdownHook(new Thread(eurekaClient::shutdown)); } } ``` -------------------------------- ### DNS TXT Records for Zone Hostnames Source: https://github.com/netflix/eureka/wiki/Deploying-Eureka-Servers-in-EC2 Recursively define TXT records for each zone to map zone DNS names to specific EC2 instance hostnames. Space-delimit multiple hostnames if a zone has more than one. ```dns txt.us-east-1c.mydomaintest.netflix.net="ec2-552-627-568-165.compute-1.amazonaws.com" "ec2-368-101-182-134.compute-1.amazonaws.com" txt.us-east-1d.mydomaintest.netflix.net="ec2-552-627-568-170.compute-1.amazonaws.com" txt.us-east-1e.mydomaintest.netflix.net="ec2-500-179-285-592.compute-1.amazonaws.com" ``` -------------------------------- ### Configure Eureka Homepage and Status URLs Source: https://github.com/netflix/eureka/wiki/Integrating-Eureka-and-Asgard Specify various URLs for Asgard to link to Eureka's status and home pages. ```properties eureka.homePageUrl ``` ```properties eureka.homePageUrlPath ``` ```properties eureka.statusPageUrl ``` ```properties eureka.statusPageUrlPath ``` -------------------------------- ### Eureka Client Properties Configuration Source: https://context7.com/netflix/eureka/llms.txt Configure the Eureka client by placing a `eureka-client.properties` file on the classpath. Ensure the four minimum required properties are set: `eureka.name`, `eureka.port`, `eureka.vipAddress`, and `eureka.serviceUrl.default`. ```properties eureka.name=my-app eureka.port=8080 eureka.vipAddress=my-app.mydomain.com eureka.serviceUrl.default=http://localhost:8761/eureka/ ``` -------------------------------- ### Set Instance Status to UP Source: https://github.com/netflix/eureka/wiki/Understanding-eureka-client-server-communication Explicitly set the instance status to UP to make it available for serving traffic. This should be called after application-specific initializations are complete. ```java ApplicationInfoManager.getInstance().setInstanceStatus(InstanceStatus.UP); ``` -------------------------------- ### Eureka Client Properties for DNS Configuration Source: https://github.com/netflix/eureka/wiki/Deploying-Eureka-Servers-in-EC2 Configure these properties in `eureka-client.properties` for both Eureka servers and clients to enable DNS lookups and specify domain, port, and context for service discovery. ```properties eureka.shouldUseDns=true euroka.eurekaServer.domainName=mydomaintest.netflix.net euroka.eurekaServer.port=7001 euroka.eurekaServer.context=eureka/v2 ``` -------------------------------- ### Clone Eureka Repository Source: https://github.com/netflix/eureka/wiki/Building-Eureka-Client-and-Server Use this command to download the Eureka source code from GitHub. ```sh git clone https://github.com/Netflix/eureka.git ``` -------------------------------- ### Heartbeat (Renew Lease) Source: https://context7.com/netflix/eureka/llms.txt Send a heartbeat to keep the instance registration alive. If no heartbeat is received for 90 seconds, the server evicts the instance. ```APIDOC ## PUT /eureka/v2/apps/{appId}/{instanceId} ### Description Send a heartbeat to keep the instance registration alive. If no heartbeat is received for 90 seconds, the server evicts the instance. ### Method PUT ### Endpoint /eureka/v2/apps/{appId}/{instanceId} ### Parameters #### Path Parameters - **appId** (string) - Required - The ID of the application. - **instanceId** (string) - Required - The ID of the instance. ### Request Example ```bash curl -X PUT \ http://eureka-server:8761/eureka/v2/apps/MY-SERVICE/myhost.example.com \ -H 'Content-Type: application/json' ``` ### Response #### Success Response (200) Indicates a successful heartbeat. #### Error Response (404) Indicates the instance is not registered and needs to be re-registered. ``` -------------------------------- ### Define Interest for Applications Source: https://github.com/netflix/eureka/wiki/Eureka-2.0-Client-Configuration-And-Use Create an interest to filter instances by application names. This is useful for targeting specific services. ```java Interest myInterest = Interests.forApplications("WriteServer", "ReadServer"); ``` -------------------------------- ### Eureka Client Configuration Properties Source: https://github.com/netflix/eureka/wiki/Configuring-Eureka These are the minimum required properties for Eureka client configuration. They should be placed in the eureka-client.properties file in your classpath. ```properties Application Name (eureka.name) Application Port (eureka.port) Virtual HostName (eureka.vipAddress) Eureka Service Urls (eureka.serviceUrls) ``` -------------------------------- ### Dynamically Set Metadata via Custom EurekaInstanceConfig Source: https://github.com/netflix/eureka/wiki/Overriding-Default-Configurations Implement a custom EurekaInstanceConfig and override getMetadataMap() to dynamically provide metadata. This allows for runtime-generated metadata. ```java public Map getMetadataMap() { // return metadata map } ``` -------------------------------- ### Updating and Unregistering an Instance with Eureka Client Source: https://github.com/netflix/eureka/wiki/Eureka-2.0-Client-Configuration-And-Use Manages instance registration using a BehaviorSubject. Initial registration occurs when the first instance info is emitted. Subsequent emissions update the instance information. Unsubscribing from the registration client unregisters the instance. ```java BehaviorSubject infoSubject = BehaviorSubject.create(); Subscription subscription = registrationClient.register(infoSubject).subscribe(); // initial registration infoSubject.onNext(myInstanceInfo); // some business logic that changed instanceInfo // update instanceInfo InstanceInfo updatedInfo = new Builder().withInstanceInfo(myInstanceInfo).withStatus(Status.DOWN).build(); infoSubject.onNext(updatedInfo); // unregistering subscription.unsubscribe(); ``` -------------------------------- ### Copy Eureka Server WAR to Tomcat Source: https://github.com/netflix/eureka/wiki/Running-the-Demo-Application Copies the built Eureka server WAR artifact to the Tomcat deployment directory. Ensure to replace 'XXX-SNAPSHOT' with the actual version. ```bash cp ./eureka-server/build/libs/eureka-server-XXX-SNAPSHOT.war $TOMCAT_HOME/webapps/eureka.war ``` -------------------------------- ### Registering a Non-Java Service Instance with Eureka via REST API Source: https://context7.com/netflix/eureka/llms.txt Register a non-Java service instance with Eureka using a POST request to `/eureka/v2/apps/{appId}`. The request body should be in JSON or XML format, specifying instance details like hostname, IP address, ports, and metadata. ```bash # Register instance via curl (JSON) curl -X POST \ http://eureka-server:8761/eureka/v2/apps/MY-SERVICE \ -H 'Content-Type: application/json' \ -d '{ "instance": { "hostName": "myhost.example.com", "app": "MY-SERVICE", "ipAddr": "10.0.0.5", "vipAddress": "myservice.internal.net", "secureVipAddress": "myservice.internal.net", "status": "UP", "port": {"$”: 8080, "@enabled": "true"}, "securePort": {"$”: 8443, "@enabled": "false"}, "homePageUrl": "http://myhost.example.com:8080/", "statusPageUrl": "http://myhost.example.com:8080/info", "healthCheckUrl": "http://myhost.example.com:8080/health", "dataCenterInfo": { "@class": "com.netflix.appinfo.MyDataCenterInfo", "name": "MyOwn" }, "leaseInfo": { "evictionDurationInSecs": 90 }, "metadata": { "version": "2.1.0", "environment": "production" } } }' # Expected response: HTTP 204 No Content ``` -------------------------------- ### Configure Eureka Metadata via Properties Source: https://github.com/netflix/eureka/wiki/Overriding-Default-Configurations Add custom key-value pairs to Eureka's metadata map by setting properties in the configuration file. The format is eureka.metadata.yourKey=yourValue. ```properties eureka.metadata.mykey=myvalue ``` -------------------------------- ### Status Override and Deregistration Source: https://context7.com/netflix/eureka/llms.txt Manage instance lifecycle operations: take out of service, restore to service, and cancel (deregister). ```APIDOC ## PUT /eureka/v2/apps/{appId}/{instanceId}/status ### Description Take an instance out of service or restore it to service. ### Method PUT ### Endpoint /eureka/v2/apps/{appId}/{instanceId}/status ### Parameters #### Path Parameters - **appId** (string) - Required - The ID of the application. - **instanceId** (string) - Required - The ID of the instance. #### Query Parameters - **value** (string) - Required - The status value. Use 'OUT_OF_SERVICE' to take out of service, or 'UP' to restore to service. ### Response #### Success Response (200) Indicates the status update was successful. #### Error Response (500) Indicates a failure during the status update. ### Request Example ```bash curl -X PUT \ "http://eureka-server:8761/eureka/v2/apps/MY-SERVICE/myhost.example.com/status?value=OUT_OF_SERVICE" ``` ``` ```APIDOC ## DELETE /eureka/v2/apps/{appId}/{instanceId}/status ### Description Restore an instance to 'UP' status by removing any status override. ### Method DELETE ### Endpoint /eureka/v2/apps/{appId}/{instanceId}/status ### Parameters #### Path Parameters - **appId** (string) - Required - The ID of the application. - **instanceId** (string) - Required - The ID of the instance. #### Query Parameters - **value** (string) - Required - Set to 'UP' to remove the status override. ### Response #### Success Response (200) Indicates the status override was successfully removed. #### Error Response (500) Indicates a failure during the status override removal. ### Request Example ```bash curl -X DELETE \ "http://eureka-server:8761/eureka/v2/apps/MY-SERVICE/myhost.example.com/status?value=UP" ``` ``` ```APIDOC ## PUT /eureka/v2/apps/{appId}/{instanceId}/metadata ### Description Add or update a key-value pair in the instance's metadata. ### Method PUT ### Endpoint /eureka/v2/apps/{appId}/{instanceId}/metadata ### Parameters #### Path Parameters - **appId** (string) - Required - The ID of the application. - **instanceId** (string) - Required - The ID of the instance. #### Query Parameters - **key** (string) - Required - The metadata key. - **value** (string) - Required - The metadata value. ### Response #### Success Response (200) Indicates the metadata was successfully added or updated. ### Request Example ```bash curl -X PUT \ "http://eureka-server:8761/eureka/v2/apps/MY-SERVICE/myhost.example.com/metadata?deployedAt=2024-01-15T10:00:00Z" ``` ``` ```APIDOC ## DELETE /eureka/v2/apps/{appId}/{instanceId} ### Description Deregister (cancel) an instance from the registry. ### Method DELETE ### Endpoint /eureka/v2/apps/{appId}/{instanceId} ### Parameters #### Path Parameters - **appId** (string) - Required - The ID of the application. - **instanceId** (string) - Required - The ID of the instance. ### Response #### Success Response (200) Indicates the instance was successfully deregistered. #### Error Response (500) Indicates a failure during the deregistration process. ### Request Example ```bash curl -X DELETE \ http://eureka-server:8761/eureka/v2/apps/MY-SERVICE/myhost.example.com ``` ``` -------------------------------- ### REST API — Register a New Instance Source: https://context7.com/netflix/eureka/llms.txt Register a non-Java service instance with the Eureka server using the REST API directly. This involves a POST request to `/eureka/v2/apps/{appId}` with a JSON or XML body. ```APIDOC ## REST API — Register a New Instance Register a non-Java service instance with the Eureka server using the REST API directly. Use `POST /eureka/v2/apps/{appId}` with a JSON or XML body. ```bash # Register instance via curl (JSON) curl -X POST \ http://eureka-server:8761/eureka/v2/apps/MY-SERVICE \ -H 'Content-Type: application/json' \ -d '{ "instance": { "hostName": "myhost.example.com", "app": "MY-SERVICE", "ipAddr": "10.0.0.5", "vipAddress": "myservice.internal.net", "secureVipAddress": "myservice.internal.net", "status": "UP", "port": {"$”: 8080, "@enabled": "true"}, "securePort": {"$”: 8443, "@enabled": "false"}, "homePageUrl": "http://myhost.example.com:8080/", "statusPageUrl": "http://myhost.example.com:8080/info", "healthCheckUrl": "http://myhost.example.com:8080/health", "dataCenterInfo": { "@class": "com.netflix.appinfo.MyDataCenterInfo", "name": "MyOwn" }, "leaseInfo": { "evictionDurationInSecs": 90 }, "metadata": { "version": "2.1.0", "environment": "production" } } }' # Expected response: HTTP 204 No Content ``` ``` -------------------------------- ### Add Eureka Client Dependency Source: https://context7.com/netflix/eureka/llms.txt Include the Eureka client library in your project using Maven or Gradle to enable service registration and discovery. ```xml com.netflix.eureka eureka-client 1.10.17 ``` ```groovy dependencies { implementation 'com.netflix.eureka:eureka-client:1.10.17' } ``` -------------------------------- ### Eureka Server Self-Preservation Configuration Source: https://context7.com/netflix/eureka/llms.txt Configure Eureka server's self-preservation mode via `eureka-server.properties`. Disabling is not recommended for production. ```properties # eureka-server.properties # Disable self-preservation (useful for local dev/testing — NOT recommended for production) eureka.enableSelfPreservation=false # Threshold: fraction of expected renewals that must be received to avoid self-preservation # Default is 0.85 (85%). Lower this value if clients have flapping heartbeats. eureka.renewalPercentThreshold=0.85 # Time window (ms) in which renewal count is evaluated (default: 15 mins) # eureka.renewalThresholdUpdateIntervalMs=900000 # Reduce startup sync wait for local development (do NOT use in production clusters) eureka.waitTimeInMsWhenSyncEmpty=0 eureka.numberRegistrySyncRetries=0 # Enable batched replication between server peers for higher efficiency eureka.shouldBatchReplication=true ``` -------------------------------- ### Buffer and Snapshot Change Notifications Source: https://github.com/netflix/eureka/wiki/Eureka-2.0-Client-Configuration-And-Use Apply transformations to buffer notifications into delta lists and then into full snapshot lists. Emits a new snapshot when any change occurs. ```java interestClient.forInterest(forFullRegistry()) .compose(ChangeNotificationFunctions.buffers()) .compose(ChangeNotificationFunctions.snapshots()) .subscribe(new Subscriber>() { @Override public void onCompleted() { System.out.println("Change notification stream closed"); } @Override public void onError(Throwable e) { System.out.println("Error in the notification channel: " + e); } @Override public void onNext(LinkedHashSet instanceInfos) { System.out.println("Received new snapshot: " + instanceInfos); } }); ``` -------------------------------- ### Taking a Service Out of Traffic (OUT_OF_SERVICE) Source: https://context7.com/netflix/eureka/llms.txt Mark an instance as OUT_OF_SERVICE for zero-downtime deployments, maintenance windows, or rollbacks without triggering eviction. This allows for graceful handling of traffic. ```APIDOC ## Taking a Service Out of Traffic (OUT_OF_SERVICE) Mark an instance as `OUT_OF_SERVICE` for zero-downtime deployments, maintenance windows, or rollbacks without triggering eviction. ```java import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.InstanceInfo.InstanceStatus; public class DeploymentController { private final ApplicationInfoManager applicationInfoManager; public DeploymentController(ApplicationInfoManager applicationInfoManager) { this.applicationInfoManager = applicationInfoManager; } public void takeOutOfTraffic() { // Clients will stop routing new requests here within ~30 seconds applicationInfoManager.setInstanceStatus(InstanceStatus.OUT_OF_SERVICE); System.out.println("Instance is OUT_OF_SERVICE — draining connections"); } public void returnToTraffic() { applicationInfoManager.setInstanceStatus(InstanceStatus.UP); System.out.println("Instance is back UP"); } public void beginShutdown() { takeOutOfTraffic(); // Wait for in-flight requests to complete try { Thread.sleep(30_000); } catch (InterruptedException ignored) {} applicationInfoManager.setInstanceStatus(InstanceStatus.DOWN); } } ``` ``` -------------------------------- ### Composite Interest Subscription in Eureka Client API Source: https://github.com/netflix/eureka/wiki/Eureka-2.0-Architecture-Overview Demonstrates how to combine multiple atomic interests using the Eureka client API. Use this for complex subscription scenarios involving multiple applications with different matching operators. ```java Interests.forSome( Interests.forApplications(Operator.Like, "eureka.*"), Interests.forApplications(Operator.Equals, "atlas") ); ``` -------------------------------- ### Eureka Client Properties Configuration Source: https://context7.com/netflix/eureka/llms.txt Configure Eureka client settings such as service name, port, Eureka server location, and DNS usage. These properties are typically placed in `src/main/resources/eureka-client.properties`. ```properties # --- Instance Identity (for registration) --- eu.name=myBackendService eu.port=8080 eu.vipAddress=mybackend.internal.net eu.region=us-east-1 # --- Eureka Server Location --- eu.preferSameZone=true eu.shouldUseDns=false eu.serviceUrl.default=http://eureka-server-host:8761/eureka/v2/ # --- Multi-zone AWS example (property-based) --- # eureka.us-east-1.availabilityZones=us-east-1c,us-east-1d,us-east-1e # eureka.serviceUrl.us-east-1c=http://ec2-1-2-3-4.compute-1.amazonaws.com:7001/eureka/v2/ # eureka.serviceUrl.us-east-1d=http://ec2-5-6-7-8.compute-1.amazonaws.com:7001/eureka/v2/ # --- DNS-based server discovery --- # eureka.shouldUseDns=true # eureka.eurekaServer.domainName=mydomaintest.netflix.net # eureka.eurekaServer.port=7001 # eureka.eurekaServer.context=eureka/v2 # --- Decoder --- eu.decoderName=JacksonJson # --- Disable registration (query-only client) --- # eureka.registration.enabled=false ``` -------------------------------- ### Add Eureka 2.0 Client as Gradle Dependency Source: https://github.com/netflix/eureka/wiki/Eureka-2.0-Client-Configuration-And-Use Include the eureka2-client library in your Gradle project to use Eureka 2.0 features. Ensure you are using the latest release for fixes. ```gradle dependencies { compile "com.netflix.eureka:eureka2-client:2.0.0-rc.2" } ``` -------------------------------- ### Add Eureka Client as Maven Dependency Source: https://github.com/netflix/eureka/wiki/Configuring-Eureka Include this dependency in your pom.xml to add the Eureka client to your project. Always try to use the latest release for fixes. ```xml com.netflix.eureka eureka-client 1.1.16 ``` -------------------------------- ### Configure Eureka Service URLs per Zone Source: https://github.com/netflix/eureka/wiki/Deploying-Eureka-Servers-in-EC2 Define the service URLs for each availability zone where Eureka servers are listening. Multiple servers within a zone can be specified using a comma-delimited list. ```properties eureka.serviceUrl.us-east-1c=http://ec2-552-627-568-165.compute-1.amazonaws.com:7001/eureka/v2/,http://ec2-368-101-182-134.compute-1.amazonaws.com:7001/eureka/v2/ ``` ```properties eureka.serviceUrl.us-east-1d=http://ec2-552-627-568-170.compute-1.amazonaws.com:7001/eureka/v2/ ``` ```properties eureka.serviceUrl.us-east-1e=http://ec2-500-179-285-592.compute-1.amazonaws.com:7001/eureka/v2/ ``` -------------------------------- ### Configure Eureka Instance Self-Identification Source: https://github.com/netflix/eureka/wiki/Eureka-2.0-Server-Configuration-And-Use Sets up instance information for a Eureka server, including its application name, VIP address, and data center type. This configuration is required for each server to identify itself. ```properties eureka.instanceInfo.appName=eureka-write-cluster eureka.instanceInfo.vipAddress=eureka-write-cluster eureka.dataCenterInfo.type=Basic ``` -------------------------------- ### Adding Custom Metadata to a Registration Source: https://context7.com/netflix/eureka/llms.txt Attach arbitrary key/value metadata to an instance's registration for use by consumers. This can be done via properties file, custom EurekaInstanceConfig, or by reading from a discovered instance. ```APIDOC ## Adding Custom Metadata to a Registration Attach arbitrary key/value metadata to an instance's registration for use by consumers (e.g., version tags, deployment color, cluster name). ```java // Option 1: via properties file // eureka.metadata.version=1.4.2 // eureka.metadata.color=blue // eureka.metadata.cluster=primary // Option 2: via custom EurekaInstanceConfig import com.netflix.appinfo.PropertiesInstanceConfig; import java.util.HashMap; import java.util.Map; public class CustomInstanceConfig extends PropertiesInstanceConfig { @Override public Map getMetadataMap() { Map meta = new HashMap<>(super.getMetadataMap()); meta.put("version", "1.4.2"); meta.put("color", "blue"); meta.put("deploymentId", System.getenv("DEPLOYMENT_ID")); return meta; } } // Option 3: reading metadata from a discovered instance import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.EurekaClient; public class MetadataReader { public static void readMetadata(EurekaClient eurekaClient) { InstanceInfo instance = eurekaClient.getNextServerFromEureka("mybackend.internal.net", false); String version = instance.getMetadata().get("version"); // "1.4.2" String color = instance.getMetadata().get("color"); // "blue" System.out.println("Connecting to version=" + version + " color=" + color); } } ``` ```