1. 程式人生 > >Eureka 的 Application Service 客戶端的註冊以及執行示例

Eureka 的 Application Service 客戶端的註冊以及執行示例

        Eureka 伺服器架起來了(關於架設步驟參考部落格《Linux 下 Eureka 伺服器的部署》),現在如何把我們要負載均衡的伺服器(也就是從 Application Client 接收請求並返回一個響應的 Application Service)註冊到 Eureka?本文以一個示例介紹 Eureka Application Service 客戶端的 Eureka 生命週期(包括啟動時的註冊、侍服示例、關閉時的取消註冊)情況,相信讀完本文之後,讀者可以對 Eureka 的 Application Service 角色有了一個進一步瞭解,而且完全可以把自己的服務加進 Eureka。
        1. Eureka 伺服器啟動
        本文 demo 要求 Eureka Server 已經部署好,並已經啟動。關於架設步驟參考部落格《
Linux 下 Eureka 伺服器的部署
》。
        Eureka 伺服器啟動以後,可以通過 http://serverIP:8080/eureka/ 或者 http://serverIP:8080/eureka/v2/apps/ 瀏覽已註冊到 Eureka 的 Application Service。比如作者在開發環境 PC 訪問伺服器端的 http://serverIP:8080/eureka/v2/apps/,頁面返回結果如下:
<applications>
	<versions__delta>1</versions__delta>
	<apps__hashcode>UP_1_</apps__hashcode>
	<application>
		<name>EUREKA</name>
		<instance>
			<hostName>localhost.localdomain</hostName>
			<app>EUREKA</app>
			<ipAddr>127.0.0.1</ipAddr>
			<status>UP</status>
			<overriddenstatus>UNKNOWN</overriddenstatus>
			<port enabled="true">8080</port>
			<securePort enabled="false">443</securePort>
			<countryId>1</countryId>
			<dataCenterInfo
				class="com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo">
				<name>MyOwn</name>
			</dataCenterInfo>
			<leaseInfo>
				<renewalIntervalInSecs>30</renewalIntervalInSecs>
				<durationInSecs>90</durationInSecs>
				<registrationTimestamp>1404789864122</registrationTimestamp>
				<lastRenewalTimestamp>1404798147096</lastRenewalTimestamp>
				<evictionTimestamp>0</evictionTimestamp>
				<serviceUpTimestamp>1404789841811</serviceUpTimestamp>
			</leaseInfo>
			<metadata class="java.util.Collections$EmptyMap" />
			<appGroupName>UNKNOWN</appGroupName>
			<homePageUrl>http://localhost.localdomain:8080/</homePageUrl>
			<statusPageUrl>http://localhost.localdomain:8080/Status</statusPageUrl>
			<healthCheckUrl>http://localhost.localdomain:8080/healthcheck</healthCheckUrl>
			<vipAddress>eureka.mydomain.net</vipAddress>
			<isCoordinatingDiscoveryServer>true</isCoordinatingDiscoveryServer>
			<lastUpdatedTimestamp>1404789864122</lastUpdatedTimestamp>
			<lastDirtyTimestamp>1404789841863</lastDirtyTimestamp>
			<actionType>ADDED</actionType>
		</instance>
	</application>
</applications>

        apps__hashcode 是 1,可以看出目前只有一個 Application Service 註冊到了 Eureka Server,這個名為 Eureka 的 Application Service 只有一個例項,就是這臺 Eureka Server 它自己 - localhost.localdomain。為何 Eureka Server 自己也是一個 Application Service 呢?這也是 Eureka 架構健壯性 feature 之一,Eureka Server 之間也會相互註冊,而且還會將註冊到自己的 Application Service 註冊給其他 Eureka Server,避免了一臺 Eureka Server 宕機所造成的區域性服務癱瘓。
        2. Application Service 配置檔案的編寫

        我們的負載均衡伺服器就用官方提供 demo 裡的 sampleservice 下的 sample-eureka-service.properties 即可,當然還要根據實際情況修正一下,比如把 eureka.name 改為我們自定義的 Application 名以區分開其他服務,把 eureka.port(本服務將會執行並侍服請求的埠)改為我們的 Service 伺服器開放的侍服埠 1935,eureka.serviceUrl.default(預設情況下本服務將要註冊到的 Eureka 伺服器):http://serverIP:8080/eureka/v2/
###Eureka Client configuration for Sample Eureka Service


#Properties based configuration for eureka client. The properties specified here is mostly what the users
#need to change. All of these can be specified as a java system property with -D option (eg)-Deureka.region=us-east-1
#For additional tuning options refer <url to go here>




#Region where eureka is deployed -For AWS specify one of the AWS regions, for other datacenters specify a arbitrary string
#indicating the region.This is normally specified as a -D option (eg) -Deureka.region=us-east-1
eureka.region=default


#Name of the application to be identified by other services


eureka.name=sampleservice


#Virtual host name by which the clients identifies this service
eureka.vipAddress=sampleservice.mydomain.net


#The port where the service will be running and serving requests
eureka.port=1935


#For eureka clients running in eureka server, it needs to connect to servers in other zones
eureka.preferSameZone=false


#Change this if you want to use a DNS based lookup for determining other eureka servers. For example
#of specifying the DNS entries, check the eureka-client-test.properties, eureka-client-prod.properties
eureka.shouldUseDns=false


eureka.us-east-1.availabilityZones=default


eureka.serviceUrl.default=http://serverIP:8080/eureka/v2/

        3. 日誌配置
        就用官方提供 demo 裡的 sampleservice 下的 log4j.properties 即可,當然還要根據實際需要修正一下,比如給 com.defonds.wms.module.server 包的輸出級別設定為 DEBUG(log4j.properties 追加 log4j.logger.com.defonds.wms.module.server=DEBUG),以方便我們研發期跟蹤除錯。
log4j.rootCategory=INFO,stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %-5p %C:%L [%t] [%M] %m%n

        4. Application Service 啟動時註冊 Eureka
        我們希望每臺負載均衡伺服器在啟動時就註冊給 Eureka,以及時承擔負載。註冊程式碼如下所示:
    private static final DynamicPropertyFactory configInstance = com.netflix.config.DynamicPropertyFactory.getInstance();


    private static final Logger logger = LoggerFactory.getLogger(SampleEurekaService.class);


    public void registerWithEureka() {
        // Register with Eureka
        DiscoveryManager.getInstance().initComponent(
                new MyDataCenterInstanceConfig(),
                new DefaultEurekaClientConfig());
        ApplicationInfoManager.getInstance().setInstanceStatus(
                InstanceStatus.UP);
	}

        第一句載入本地配置檔案,initComponent 句根據配置初始化這臺 Eureka Application Service,並且註冊到 Eureka Server,setInstanceStatus 句指示本臺 Application Service 已啟動,準備好侍服網路請求。
        5. Application Service 侍服網路請求
        Application Service 的 Eureka Server 初始化以及註冊是非同步的,需要一段時間,我們想要在確認初始化並註冊成功之後,提供一個 Socket 服務,以供網路請求。demo 需要,這個服務是一次性的,只提供一次 Socket 侍服。侍服完一次請求後,本 Socket 服務就關閉,並將自己從 Eureka Server 取消註冊。
        String vipAddress = configInstance.getStringProperty(
                "eureka.vipAddress", "sampleservice.mydomain.net").get();
        InstanceInfo nextServerInfo = null;
        while (nextServerInfo == null) {
            try {
                nextServerInfo = DiscoveryManager.getInstance()
                .getDiscoveryClient()
                .getNextServerFromEureka(vipAddress, false);
            } catch (Throwable e) {
                System.out
                .println("Waiting for service to register with eureka..");


                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }


            }
        }
        System.out.println("Service started and ready to process requests..");


        try {
            ServerSocket serverSocket = new ServerSocket(configInstance
                    .getIntProperty("eureka.port", 8010).get());
            final Socket s = serverSocket.accept();
            System.out
            .println("Client got connected..Processing request from the client");
            processRequest(s);


        } catch (IOException e) {
            e.printStackTrace();
        }

        Socket 侍服 processRequest 方法詳細如下:
    private void processRequest(final Socket s) {
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    s.getInputStream()));
            String line = rd.readLine();
            if (line != null) {
                System.out.println("Received the request from the client.");
            }
            PrintStream out = new PrintStream(s.getOutputStream());
            System.out.println("Sending the response to the client...");


            out.println("Reponse at " + new Date());


        } catch (Throwable e) {
            System.err.println("Error processing requests");
        } finally {
            if (s != null) {
                try {
                    s.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }


    }	

        6. Application Service 關閉時取消註冊
        就像 Spring 管理的物件,初始化、銷燬都統一管理起來一樣,我們希望本臺 Application Service 例項在關閉時也能將自身佔用的系統資源釋放出來(比如任務列表的執行緒關閉),而且取消掉 Eureka 伺服器的註冊。
    public void unRegisterWithEureka() {
        // Un register from eureka.
        DiscoveryManager.getInstance().shutdownComponent();
    }

        7. 執行 demo
        現在我們把完整的 Application Service 整理一下。
/*
 * Copyright 2012 Netflix, Inc.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */


package com.netflix.eureka;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.appinfo.MyDataCenterInstanceConfig;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.discovery.DefaultEurekaClientConfig;
import com.netflix.discovery.DiscoveryManager;


/**
 * Sample Eureka service that registers with Eureka to receive and process
 * requests.
 * 
 * <p>
 * This example just receives one request and exits once it receives the request
 * after processing it.
 * </p>
 * 
 * @author Karthik Ranganathan
 * 
 */
public class SampleEurekaService {
	
    private static final DynamicPropertyFactory configInstance = com.netflix.config.DynamicPropertyFactory
    .getInstance();


    private static final Logger logger = LoggerFactory
    .getLogger(SampleEurekaService.class);


    public void registerWithEureka() {
        // Register with Eureka
        DiscoveryManager.getInstance().initComponent(
                new MyDataCenterInstanceConfig(),
                new DefaultEurekaClientConfig());
        ApplicationInfoManager.getInstance().setInstanceStatus(
                InstanceStatus.UP);
        String vipAddress = configInstance.getStringProperty(
                "eureka.vipAddress", "sampleservice.mydomain.net").get();
        InstanceInfo nextServerInfo = null;
        while (nextServerInfo == null) {
            try {
                nextServerInfo = DiscoveryManager.getInstance()
                .getDiscoveryClient()
                .getNextServerFromEureka(vipAddress, false);
            } catch (Throwable e) {
                System.out
                .println("Waiting for service to register with eureka..");


                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }


            }
        }
        System.out.println("Service started and ready to process requests..");


        try {
            ServerSocket serverSocket = new ServerSocket(configInstance
                    .getIntProperty("eureka.port", 8010).get());
            final Socket s = serverSocket.accept();
            System.out
            .println("Client got connected..Processing request from the client");
            processRequest(s);


        } catch (IOException e) {
            e.printStackTrace();
        }
        this.unRegisterWithEureka();
        System.out.println("Shutting down server.Demo over.");


    }


    public void unRegisterWithEureka() {
        // Un register from eureka.
        DiscoveryManager.getInstance().shutdownComponent();
    }


    private void processRequest(final Socket s) {
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    s.getInputStream()));
            String line = rd.readLine();
            if (line != null) {
                System.out.println("Received the request from the client.");
            }
            PrintStream out = new PrintStream(s.getOutputStream());
            System.out.println("Sending the response to the client...");


            out.println("Reponse at " + new Date());


        } catch (Throwable e) {
            System.err.println("Error processing requests");
        } finally {
            if (s != null) {
                try {
                    s.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }


    }


    public static void main(String args[]) {
        SampleEurekaService sampleEurekaService = new SampleEurekaService();
        sampleEurekaService.registerWithEureka();
    }


}

        很明顯我們的 SampleEurekaService 類需要很多依賴包,這些包都在 eureka-server-1.1.134.war 包裡的 WEB-INF/lib 目錄下,直接拷貝進我們 demo 的 CLASSPATH,不用一個個去找了,還避免了版本衝突所帶來的不必要麻煩。eureka-client-1.1.134.jar 可以去 http://mvnrepository.com/artifact/com.netflix.eureka/eureka-client/1.1.134 下載,或者直接 maven 依賴匯入:
<dependency>
	<groupId>com.netflix.eureka</groupId>
	<artifactId>eureka-client</artifactId>
	<version>1.1.134</version>
</dependency>

        類完成了、環境配置好了,接下來把第二、三步寫好的 sample-eureka-service.properties、log4j.properties 也拷貝進 CLASSPATH,接下來就可以執行 demo 了。直接 run SampleEurekaService,發現報以下錯誤:
2014-07-07 17:01:50,141 WARN  com.netflix.config.sources.URLConfigurationSource:120 [main] [<init>] No URLs will be polled as dynamic configuration sources.
2014-07-07 17:01:50,144 INFO  com.netflix.config.sources.URLConfigurationSource:121 [main] [<init>] To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2014-07-07 17:01:50,178 INFO  com.netflix.config.DynamicPropertyFactory:281 [main] [getInstance] DynamicPropertyFactory is initialized with configuration sources: [email protected]
2014-07-07 17:01:58,982 WARN  com.netflix.appinfo.PropertiesInstanceConfig:349 [main] [init] Cannot find the properties specified : eureka-client. This may be okay if there are other environment specific properties or the configuration is installed with a different mechanism.
2014-07-07 17:02:00,140 WARN  com.netflix.discovery.DefaultEurekaClientConfig:95 [main] [init] Cannot find the properties specified : eureka-client. This may be okay if there are other environment specific properties or the configuration is installed with a different mechanism.
2014-07-07 17:02:03,559 INFO  com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider:79 [main] [get] Setting initial instance status as: STARTING
Exception in thread "main" java.lang.RuntimeException: Failed to initialize DiscoveryClient!
at com.netflix.discovery.DiscoveryClient.<init>(DiscoveryClient.java:235)
at com.netflix.discovery.DiscoveryClient.<init>(DiscoveryClient.java:169)
at com.netflix.discovery.DiscoveryManager.initComponent(DiscoveryManager.java:84)
at com.netflix.eureka.SampleEurekaService.registerWithEureka(SampleEurekaService.java:60)
at com.netflix.eureka.SampleEurekaService.main(SampleEurekaService.java:139)
Caused by: java.lang.IllegalArgumentException: DiscoveryClient: invalid serviceUrl specified!
at com.netflix.discovery.DiscoveryClient.getEurekaServiceUrlsFromConfig(DiscoveryClient.java:574)
at com.netflix.discovery.DiscoveryClient.getDiscoveryServiceUrls(DiscoveryClient.java:1180)
at com.netflix.discovery.DiscoveryClient.<init>(DiscoveryClient.java:186)
... 4 more

        原來 Archaius 不認 sample-eureka-service.properties,沒有把我們的配置成功載入。Archaius 的官方說,Archaius 在預設情況下(就是不指定 properties 檔案的情況下)會在應用的 classpath 中尋找一個名為 config.properties 的檔案並讀取其內容作為配置屬性。
        好吧,我們把 sample-eureka-service.properties 重新命名為 config.properties,然後重新執行 SampleEurekaService。這次執行成功了,沒有再報錯。訪問伺服器端的 http://serverIP:8080/eureka/v2/apps/,顯示如下頁面資訊:
<applications>
	<versions__delta>1</versions__delta>
	<apps__hashcode>UP_2_</apps__hashcode>
	<application>
		<name>SAMPLESERVICE</name>
		<instance>
			<hostName>defonds-win7</hostName>
			<app>SAMPLESERVICE</app>
			<ipAddr>172.21.40.134</ipAddr>
			<status>UP</status>
			<overriddenstatus>UNKNOWN</overriddenstatus>
			<port enabled="true">1935</port>
			<securePort enabled="false">443</securePort>
			<countryId>1</countryId>
			<dataCenterInfo
				class="com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo">
				<name>MyOwn</name>
			</dataCenterInfo>
			<leaseInfo>
				<renewalIntervalInSecs>30</renewalIntervalInSecs>
				<durationInSecs>90</durationInSecs>
				<registrationTimestamp>1404812488643</registrationTimestamp>
				<lastRenewalTimestamp>1404812609036</lastRenewalTimestamp>
				<evictionTimestamp>0</evictionTimestamp>
				<serviceUpTimestamp>1404812458545</serviceUpTimestamp>
			</leaseInfo>
			<metadata class="java.util.Collections$EmptyMap" />
			<appGroupName>UNKNOWN</appGroupName>
			<homePageUrl>http://defonds-win7:1935/</homePageUrl>
			<statusPageUrl>http://defonds-win7:1935/Status</statusPageUrl>
			<healthCheckUrl>http://defonds-win7:1935/healthcheck</healthCheckUrl>
			<vipAddress>sampleservice.mydomain.net</vipAddress>
			<isCoordinatingDiscoveryServer>false</isCoordinatingDiscoveryServer>
			<lastUpdatedTimestamp>1404812488643</lastUpdatedTimestamp>
			<lastDirtyTimestamp>1404812513644</lastDirtyTimestamp>
			<actionType>ADDED</actionType>
		</instance>
	</application>
	<application>
		<name>EUREKA</name>
		<instance>
			<hostName>localhost.localdomain</hostName>
			<app>EUREKA</app>
			<ipAddr>127.0.0.1</ipAddr>
			<status>UP</status>
			<overriddenstatus>UNKNOWN</overriddenstatus>
			<port enabled="true">8080</port>
			<securePort enabled="false">443</securePort>
			<countryId>1</countryId>
			<dataCenterInfo
				class="com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo">
				<name>MyOwn</name>
			</dataCenterInfo>
			<leaseInfo>
				<renewalIntervalInSecs>30</renewalIntervalInSecs>
				<durationInSecs>90</durationInSecs>
				<registrationTimestamp>1404812408111</registrationTimestamp>
				<lastRenewalTimestamp>1404812618042</lastRenewalTimestamp>
				<evictionTimestamp>0</evictionTimestamp>
				<serviceUpTimestamp>1404812385938</serviceUpTimestamp>
			</leaseInfo>
			<metadata class="java.util.Collections$EmptyMap" />
			<appGroupName>UNKNOWN</appGroupName>
			<homePageUrl>http://localhost.localdomain:8080/</homePageUrl>
			<statusPageUrl>http://localhost.localdomain:8080/Status
			</statusPageUrl>
			<healthCheckUrl>http://localhost.localdomain:8080/healthcheck
			</healthCheckUrl>
			<vipAddress>eureka.mydomain.net</vipAddress>
			<isCoordinatingDiscoveryServer>true</isCoordinatingDiscoveryServer>
			<lastUpdatedTimestamp>1404812408111</lastUpdatedTimestamp>
			<lastDirtyTimestamp>1404812385985</lastDirtyTimestamp>
			<actionType>ADDED</actionType>
		</instance>
	</application>
</applications>

        apps__hashcode 變成 2 了。可以看出多了一個 defonds-win7 名字的 instance,它的 IP 地址正是我執行 demo 的 PC 地址 172.21.40.134。訪問 http://serverIP:8080/eureka/ 也可以看到該 instance:
註冊後的Eureka Server
        證明我們的 Application Service 已經成功註冊到該臺 Eureka Server。我們等待 Eureka Server 心跳訪問該 Application Service,或者自己手工訪問該 Application Service,以達成該伺服器關閉條件,將其關閉,Application Service 成功取消註冊。完整的 demo log 如下:
2014-07-08 10:06:54,124 INFO  com.netflix.config.sources.URLConfigurationSource:125 [main] [<init>] URLs to be used as dynamic configuration source: [file:/D:/javaprojects/test/bin/config.properties]
2014-07-08 10:06:54,259 INFO  com.netflix.config.DynamicPropertyFactory:281 [main] [getInstance] DynamicPropertyFactory is initialized with configuration sources: [email protected]
2014-07-08 10:08:32,464 WARN  com.netflix.appinfo.PropertiesInstanceConfig:349 [main] [init] Cannot find the properties specified : eureka-client. This may be okay if there are other environment specific properties or the configuration is installed with a different mechanism.
2014-07-08 10:08:35,592 WARN  com.netflix.discovery.DefaultEurekaClientConfig:95 [main] [init] Cannot find the properties specified : eureka-client. This may be okay if there are other environment specific properties or the configuration is installed with a different mechanism.
2014-07-08 10:08:45,835 INFO  com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider:79 [main] [get] Setting initial instance status as: STARTING
2014-07-08 10:08:46,331 WARN  com.netflix.discovery.DiscoveryClient:1339 [main] [getZoneOffset] DISCOVERY: Could not pick a zone based on preferred zone settings. My zone - defaultZone, preferSameZone- false. Defaulting to defaultZone
2014-07-08 10:08:49,276 INFO  com.netflix.discovery.DiscoveryClient:646 [main] [fetchRegistry] Disable delta property : false
2014-07-08 10:08:49,277 INFO  com.netflix.discovery.DiscoveryClient:647 [main] [fetchRegistry] Single vip registry refresh property : null
2014-07-08 10:08:49,277 INFO  com.netflix.discovery.DiscoveryClient:648 [main] [fetchRegistry] Force full registry fetch : false
2014-07-08 10:08:49,277 INFO  com.netflix.discovery.DiscoveryClient:649 [main] [fetchRegistry] Application is null : false
2014-07-08 10:08:49,277 INFO  com.netflix.discovery.DiscoveryClient:650 [main] [fetchRegistry] Registered Applications size is zero : true
2014-07-08 10:08:49,278 INFO  com.netflix.discovery.DiscoveryClient:652 [main] [fetchRegistry] Application version is -1: true
2014-07-08 10:08:49,705 INFO  com.netflix.discovery.DiscoveryClient:992 [main] [makeRemoteCall] Finished a call to service url http://serverIP:8080/eureka/v2/ and url path apps/ with status code 200.
2014-07-08 10:08:49,706 INFO  com.netflix.discovery.DiscoveryClient:758 [main] [getAndStoreFullRegistry] Getting all instance registry info from the eureka server
2014-07-08 10:08:50,501 INFO  com.netflix.discovery.DiscoveryClient:765 [main] [getAndStoreFullRegistry] The response status is 200
2014-07-08 10:08:50,504 INFO  com.netflix.discovery.DiscoveryClient:1056 [main] [initScheduledTasks] Starting heartbeat executor: renew interval is: 30
2014-07-08 10:09:20,508 INFO  com.netflix.discovery.DiscoveryClient:992 [DiscoveryClient-2] [makeRemoteCall] Finished a call to service url http://serverIP:8080/eureka/v2/ and url path apps/delta with status code 200.
2014-07-08 10:09:20,535 INFO  com.netflix.discovery.DiscoveryClient$CacheRefreshThread:1542 [DiscoveryClient-2] [run] Completed cache refresh task for discovery. All Apps hash code is Local region apps hashcode: UP_1_, is fetching remote regions? false 
2014-07-08 10:09:20,582 INFO  com.netflix.discovery.DiscoveryClient:992 [DiscoveryClient-3] [makeRemoteCall] Finished a call to service url http://serverIP:8080/eureka/v2/ and url path apps/SAMPLESERVICE/defonds-win7 with status code 404.
2014-07-08 10:09:20,599 INFO  com.netflix.discovery.DiscoveryClient$HeartbeatThread:1415 [DiscoveryClient-3] [run] DiscoveryClient_SAMPLESERVICE/defonds-win7 - Re-registering apps/SAMPLESERVICE
2014-07-08 10:09:20,600 INFO  com.netflix.discovery.DiscoveryClient:509 [DiscoveryClient-3] [register] DiscoveryClient_SAMPLESERVICE/defonds-win7: registering service...
2014-07-08 10:09:20,648 INFO  com.netflix.discovery.DiscoveryClient:992 [DiscoveryClient-3] [makeRemoteCall] Finished a call to service url http://serverIP:8080/eureka/v2/ and url path apps/SAMPLESERVICE with status code 204.
2014-07-08 10:09:20,649 INFO  com.netflix.discovery.DiscoveryClient:514 [DiscoveryClient-3] [register] DiscoveryClient_SAMPLESERVICE/defonds-win7 - registration status: 204
Waiting for service to register with eureka..
2014-07-08 10:09:30,513 INFO  com.netflix.discovery.DiscoveryClient$InstanceInfoReplicator:1476 [DiscoveryClient-2] [run] DiscoveryClient_SAMPLESERVICE/defonds-win7 - retransmit instance info with status UP
2014-07-08 10:09:30,514 INFO  com.netflix.discovery.DiscoveryClient:509 [DiscoveryClient-2] [register] DiscoveryClient_SAMPLESERVICE/defonds-win7: registering service...
2014-07-08 10:09:30,561 INFO  com.netflix.discovery.DiscoveryClient:992 [DiscoveryClient-2] [makeRemoteCall] Finished a call to service url http://serverIP:8080/eureka/v2/ and url path apps/SAMPLESERVICE with status code 204.
2014-07-08 10:09:30,562 INFO  com.netflix.discovery.DiscoveryClient:514 [DiscoveryClient-2] [register] DiscoveryClient_SAMPLESERVICE/defonds-win7 - registration status: 204
2014-07-08 10:09:50,540 INFO  com.netflix.discovery.DiscoveryClient:992 [DiscoveryClient-1] [makeRemoteCall] Finished a call to service url http://serverIP:8080/eureka/v2/ and url path apps/delta with status code 200.
2014-07-08 10:09:50,543 INFO  com.netflix.discovery.DiscoveryClient$CacheRefreshThread:1542 [DiscoveryClient-1] [run] Completed cache refresh task for discovery. All Apps hash code is Local region apps hashcode: UP_2_, is fetching remote regions? false 
2014-07-08 10:09:50,654 INFO  com.netflix.discovery.DiscoveryClient:992 [DiscoveryClient-1] [makeRemoteCall] Finished a call to service url http://serverIP:8080/eureka/v2/ and url path apps/SAMPLESERVICE/defonds-win7 with status code 404.
2014-07-08 10:09:50,654 INFO  com.netflix.discovery.DiscoveryClient$HeartbeatThread:1415 [DiscoveryClient-1] [run] DiscoveryClient_SAMPLESERVICE/defonds-win7 - Re-registering apps/SAMPLESERVICE
2014-07-08 10:09:50,654 INFO  com.netflix.discovery.DiscoveryClient:509 [DiscoveryClient-1] [register] DiscoveryClient_SAMPLESERVICE/defonds-win7: registering service...
2014-07-08 10:09:50,674 INFO  com.netflix.discovery.DiscoveryClient:992 [DiscoveryClient-1] [makeRemoteCall] Finished a call to service url http://serverIP:8080/eureka/v2/ and url path apps/SAMPLESERVICE with status code 204.
2014-07-08 10:09:50,674 INFO  com.netflix.discovery.DiscoveryClient:514 [DiscoveryClient-1] [register] DiscoveryClient_SAMPLESERVICE/defonds-win7 - registration status: 204
Service started and ready to process requests..
2014-07-08 10:10:20,548 INFO  com.netflix.discovery.DiscoveryClient:992 [DiscoveryClient-2] [makeRemoteCall] Finished a call to service url http://serverIP:8080/eureka/v2/ and url path apps/delta with status code 200.
2014-07-08 10:10:20,551 INFO  com.netflix.discovery.DiscoveryClient$CacheRefreshThread:1542 [DiscoveryClient-2] [run] Completed cache refresh task for discovery. All Apps hash code is Local region apps hashcode: UP_2_, is fetching remote regions? false 
2014-07-08 10:10:20,678 INFO  com.netflix.discovery.DiscoveryClient:992 [DiscoveryClient-1] [makeRemoteCall] Finished a call to service url http://serverIP:8080/eureka/v2/ and url path apps/SAMPLESERVICE/defonds-win7 with status code 200.
2014-07-08 10:10:50,556 INFO  com.netflix.discovery.DiscoveryClient:992 [DiscoveryClient-1] [makeRemoteCall] Finished a call to service url http://serverIP:8080/eureka/v2/ and url path apps/delta with status code 200.
2014-07-08 10:10:50,559 INFO  com.netflix.discovery.DiscoveryClient$CacheRefreshThread:1542 [DiscoveryClient-1] [run] Completed cache refresh task for discovery. All Apps hash code is Local region apps hashcode: UP_2_, is fetching remote regions? false 
2014-07-08 10:10:50,681 INFO  com.netflix.discovery.DiscoveryClient:992 [DiscoveryClient-0] [makeRemoteCall] Finished a call to service url http://serverIP:8080/eureka/v2/ and url path apps/SAMPLESERVICE/defonds-win7 with status code 200.
2014-07-08 10:11:20,563 INFO  com.netflix.discovery.DiscoveryClient:992 [DiscoveryClient-1] [makeRemoteCall] Finished a call to service url http://serverIP:8080/eureka/v2/ and url path apps/delta with status code 200.
2014-07-08 10:11:20,566 INFO  com.netflix.discovery.DiscoveryClient$CacheRefreshThread:1542 [DiscoveryClient-1] [run] Completed cache refresh task for discovery. All Apps hash code is Local region apps hashcode: UP_2_, is fetching remote regions? false 
2014-07-08 10:11:20,684 INFO  com.netflix.discovery.DiscoveryClient:992 [DiscoveryClient-1] [makeRemoteCall] Finished a call to service url http://serverIP:8080/eureka/v2/ and url path apps/SAMPLESERVICE/defonds-win7 with status code 200.
2014-07-08 10:11:50,570 INFO  com.netflix.discovery.DiscoveryClient:992 [DiscoveryClient-2] [makeRemoteCall] Finished a call to service url http://serverIP:8080/eureka/v2/ and url path apps/delta with status code 200.
2014-07-08 10:11:50,573 INFO  com.netflix.discovery.DiscoveryClient$CacheRefreshThread:1542 [DiscoveryClient-2] [run] Completed cache refresh task for discovery. All Apps hash code is Local region apps hashcode: UP_2_, is fetching remote regions? false 
2014-07-08 10:11:50,687 INFO  com.netflix.discovery.DiscoveryClient:992 [DiscoveryClient-1] [makeRemoteCall] Finished a call to service url http://serverIP:8080/eureka/v2/ and url path apps/SAMPLESERVICE/defonds-win7 with status code 200.
2014-07-08 10:12:20,579 INFO  com.netflix.discovery.DiscoveryClient:992 [DiscoveryClient-0] [makeRemoteCall] Finished a call to service url http://serverIP:8080/eureka/v2/ and url path apps/delta with status code 200.
2014-07-08 10:12:20,582 INFO  com.netflix.discovery.DiscoveryClient$CacheRefreshThread:1542 [DiscoveryClient-0] [run] Completed cache refresh task for discovery. All Apps hash code is Local region apps hashcode: UP_2_, is fetching remote regions? false 
2014-07-08 10:12:20,691 INFO  com.netflix.discovery.DiscoveryClient:992 [DiscoveryClient-0] [makeRemoteCall] Finished a call to service url http://serverIP:8080/eureka/v2/ and url path apps/SAMPLESERVICE/defonds-win7 with status code 200.
Client got connected..Processing request from the client
Received the request from the client.
Sending the response to the client...
2014-07-08 10:12:27,188 INFO  com.netflix.discovery.DiscoveryClient:992 [main] [makeRemoteCall] Finished a call to service url http://serverIP:8080/eureka/v2/ and url path apps/SAMPLESERVICE/defonds-win7 with status code 200.
2014-07-08 10:12:27,189 INFO  com.netflix.discovery.DiscoveryClient:603 [main] [unregister] DiscoveryClient_SAMPLESERVICE/defonds-win7 - deregister  status: 200
Shutting down server.Demo over.

        麻雀雖小五臟俱全,例子很簡單,但卻完整地展現了一個 Application Service 客戶端的 Eureka 生命週期。
        參考資料