Eureka Run example of application client clients

Source: Internet
Author: User
Tags aws regions log4j

The application Service client role for Eureka is described in the previous article with a demo sample. Today we continue to understand Eureka's application client client, with a simple interaction example that describes how application Client uses Eureka to get a application Service instance and send the request.
The registration and running example of the application service client for Eureka uses a socket service as a demo, which, in conjunction with this article, will request a socket client for the service.
1. Eureka Server Startup
This demo requires that Eureka Server is already deployed and has been started. About the erection step refer to the blog "Deployment of Eureka servers under Linux".
2. Application Service start
Run the small demo in Eureka's application Service client and run the sample directly (the Socket Server starts and begins to service the network request).
3. Writing the application Client configuration file
Our application Client will use the official demo in the sampleclient under the sample-eureka-client.properties can, of course, according to the actual situation to amend, such as the Eureka.serviceUrl.default (the Eureka server to which this client will be registered by default):http://serverIP:8080/eureka/v2/:
# # #Eureka Client configuration for Sample Eureka client#properties based the configuration for Eureka client. The properties specified here are mostly what's the users#need to change.  All of these can is 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 are deployed-for AWS Specify one of the AWS regions, for other D Atacenters specify a arbitrary string#indicating the region. This was normally specified as a-d option (eg)-deureka.region=us-east-1eureka.region=default#name of the application to B E identified by and Serviceseureka.name=sampleeurekaclient#virtual host name by which the clients identifies this Servic E#eureka.vipaddress=eureka.mydomain.net#the Port where the service would be running and servicing requests#eureka.port=80 #For Eureka clients running in Eureka Server, it needs-connect to servers on other Zoneseureka.prefersamezone=true#chan GE this if your want to use a DNSBased lookup for determining and other Eureka servers. For example#of specifying the DNS entries, check the eureka-client-test.properties, eureka-client-prod.propertieseureka.shouldusedns=falseeureka.us-east-1.availabilityzones= defaulteureka.serviceurl.default=http://serverip:8080/eureka/v2/

4. Log Configuration
Use the official to provide the demo in the Sampleclient under the log4j.properties can, of course, according to the actual need to correct, such as to Com.netflix.eureka package output level set to DEBUG ( Log4j.properties additional log4j.logger.com.netflix.eureka=debug), to facilitate our research and development period tracking debugging.
log4j.rootcategory=info,stdoutlog4j.appender.stdout= org.apache.log4j.consoleappenderlog4j.appender.stdout.layout= org.apache.log4j.patternlayoutlog4j.appender.stdout.layout.conversionpattern=%d%-5p%C:%L [%t] [%M]%m% Nlog4j.logger.com.netflix.eureka=debug

5. Find the application Service instance for this request
The client has to get the application service instance from Eureka Server to service this request before application service request. The code for the application Service instance looking for this request is as follows:
        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 = discoverymanager.getinstance ()                . Getdiscoveryclient ()                . Getnextserverfromeureka (vipaddress, false);

The first sentence initializes the client, and the second sentence tells Eureka that the client is in a ready state, and the next two sentences are to use Eureka to find the application service instance that is serving the request.
6. Application Client Network Request
Application Client gets Application ServiceImmediately after the network Socket request, the data information interaction.
        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:" + nextserve        Rinfo.gethostname () + "at Port" + serverport); try {System.out.println ("Connected to server.            Sending a sample request ");            PrintStream out = new PrintStream (S.getoutputstream ());            OUT.PRINTLN ("Sample request" + new Date ());            String str = NULL;            System.out.println ("Waiting for server response..");            BufferedReader rd = new BufferedReader (New InputStreamReader (S.getinputstream ()));            str = Rd.readline (); if (str! = null) {System.out. println ("Received response from server. Communication all fine using Eureka :"); System.out.println ("Exiting the client.            Demo over. ");}        Rd.close ();        } catch (IOException e) {e.printstacktrace (); }

7. Application Client Cancel registration when closed
Application Client will cancel its registration in Eureka when it is closed.
    public void Unregisterwitheureka () {        //Un register from Eureka.        Discoverymanager.getinstance (). Shutdowncomponent ();    }

8. Run Demo
Create a new project (do not run under the same project as the Application Service demo), and now we will tidy up the full application Client code.
/* * Copyright Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * You are not a use this file except in compliance with the License. * 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 are distributed on a "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.inetsocketaddress;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 client that discovers the service using Eureka and sends * requ ESTs. * * @author Karthik Ranganathan * */public class Sampleeurekaclient {private static final dynamicpropertyfactory confi        Ginstance = com.netflix.config.DynamicPropertyFactory. getinstance ();    private static final Logger Logger = loggerfactory. GetLogger (Sampleeurekaclient.class); public void Sendrequesttoserviceusingeureka () {//Register with Eureka discoverymanager.getinstance (). INITC        Omponent (New Mydatacenterinstanceconfig (), New Defaulteurekaclientconfig ());        Applicationinfomanager.getinstance (). Setinstancestatus (Instancestatus.up); String vipaddress = configinstance.Getstringproperty ("Eureka.vipaddress", "sampleservice.mydomain.net"). get (); Instanceinfo nextserverinfo = Discoverymanager.getinstance (). Getdiscoveryclient (). getnexts        Erverfromeureka (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:" + nextserve        Rinfo.gethostname () + "at Port" + serverport); try {System.out.println ("Connected to server.            Sending a sample request ");            PrintStream out = new PrintStream (S.getoutputstream ());            OUT.PRINTLN ("Sample request" + new Date ());            String str = NULL;            System.out.println ("Waiting for server response.."); BufferedReader rd = new BufferedreAder (New InputStreamReader (S.getinputstream ()));            str = Rd.readline (); if (str! = null) {System.out. println ("Received response from server.                Communication all fine using Eureka: "); System.out.println ("Exiting the client.            Demo over. ");}        Rd.close ();        } catch (IOException e) {e.printstacktrace ();    } This.unregisterwitheureka ();        } public void Unregisterwitheureka () {//Un register from Eureka.    Discoverymanager.getinstance (). Shutdowncomponent ();        } public static void Main (string[] args) {sampleeurekaclient sampleeurekaservice = new Sampleeurekaclient ();    Sampleeurekaservice.sendrequesttoserviceusingeureka (); }}

As described in the previous blog, the various dependencies are added to the CLASSPATH of this demo, and then the third to fourth step written sample-eureka-client.properties, Log4j.properties also copied into the CLASSPATH, and will Sample-eureka-client.properties renamed to Config.properties (reason reference to the previous blog), then you can run this demo. Run sampleeurekaclient, the log results are as follows:
2014-07-10 11:02:51,860 INFO com.netflix.config.sources.urlconfigurationsource:125 [main] [<init>] URLs to be Used as dynamic configuration source: [File:/d:/javaprojects/test2/bin/config.properties]
2014-07-10 11:02:51,927 INFO com.netflix.config.dynamicpropertyfactory:281 [main] [getinstance] Dynamicpropertyfactory is initialized with configuration sources: [email protected]
2014-07-10 11:02:52,060 WARN com.netflix.appinfo.propertiesinstanceconfig:349 [main] [Init] cannot find the properties s Pecified:eureka-client. This could be okay if there was other environment specific properties or the configuration was installed with a different MEC Hanism.
2014-07-10 11:02:52,065 WARN com.netflix.discovery.defaulteurekaclientconfig:95 [main] [Init] cannot find the Properties Specified:eureka-client. This could be okay if there was other environment specific properties or the configuration was installed with a different MEC Hanism.
2014-07-10 11:02:52,103 INFO com.netflix.appinfo.providers.eurekaconfigbasedinstanceinfoprovider:79 [main] [get] Setting Initial instance Status as:starting
2014-07-10 11:02:53,667 INFO com.netflix.discovery.discoveryclient:646 [main] [fetchregistry] Disable Delta Property:f Alse
2014-07-10 11:02:53,667 INFO com.netflix.discovery.discoveryclient:647 [main] [Fetchregistry] Single VIP registry Refresh Property:null
2014-07-10 11:02:53,667 INFO com.netflix.discovery.discoveryclient:648 [main] [Fetchregistry] Force full registry Fetch : false
2014-07-10 11:02:53,667 INFO com.netflix.discovery.discoveryclient:649 [main] [fetchregistry] Application is null: False
2014-07-10 11:02:53,667 INFO com.netflix.discovery.discoveryclient:650 [main] [fetchregistry] Registered Applications Size is Zero:true
2014-07-10 11:02:53,668 INFO com.netflix.discovery.discoveryclient:652 [main] [fetchregistry] Application version is-1 : True
2014-07-10 11:02:54,061 INFO com.netflix.discovery.discoveryclient:992 [main] [Makeremotecall] Finished a call to Servic e URL http://serverIP:8080/eureka/v2/and url path apps/with status code 200.
2014-07-10 11:02:54,061 INFO com.netflix.discovery.discoveryclient:758 [main] [getandstorefullregistry] Getting All Instance registry info from the Eureka server
2014-07-10 11:02:54,568 INFO com.netflix.discovery.discoveryclient:765 [main] [Getandstorefullregistry] the response Status is 200
2014-07-10 11:02:54,578 INFO com.netflix.discovery.discoveryclient:1056 [main] [Initscheduledtasks] Starting Heartbeat executor:renew Interval is:30
Connected to server. Sending a sample request
Waiting for server response:
Received response from server. Communication all fine using Eureka:
Exiting the client. Demo over.
Demonstrate that the demo obtains the application Service instance and requests success.
As you can see, application Service instance information is encapsulated under Com.netflix.appinfo.InstanceInfo, what else can we get from it? The Sampleeurekaclient class adds the following code:
        Logger.debug ("Nextserverinfo.getappgroupname ()-" + nextserverinfo.getappgroupname ());        Logger.debug ("Nextserverinfo.getappname ()-" + nextserverinfo.getappname ());        Logger.debug ("Nextserverinfo.getasgname ()-" + nextserverinfo.getasgname ());        Logger.debug ("Nextserverinfo.gethomepageurl ()-" + Nextserverinfo.gethomepageurl ());        Logger.debug ("Nextserverinfo.gethostname ()-" + nextserverinfo.gethostname ());        Logger.debug ("Nextserverinfo.getid ()-" + Nextserverinfo.getid ());        Logger.debug ("nextserverinfo.getipaddr ()-" + nextserverinfo.getipaddr ());        Logger.debug ("Nextserverinfo.getlastupdatedtimestamp ()-" + Nextserverinfo.getlastupdatedtimestamp ());        Logger.debug ("Nextserverinfo.getport ()-" + Nextserverinfo.getport ());        Logger.debug ("nextserverinfo.getsecurevipaddress ()-" + nextserverinfo.getsecurevipaddress ());        Logger.debug ("Nextserverinfo.getstatuspageurl ()-" + Nextserverinfo.getstatuspageurl ()); Logger.debug ("NextserVerinfo.getvipaddress ()-"+ nextserverinfo.getvipaddress ());        Logger.debug ("Nextserverinfo.getlastdirtytimestamp ()-" + Nextserverinfo.getlastdirtytimestamp ());        Logger.debug ("Nextserverinfo.gethealthcheckurls ()-" + nextserverinfo.gethealthcheckurls ()); Logger.debug ("Nextserverinfo.getstatus ()-" + nextserverinfo.getstatus ());

Then rerun this demo, the above statement prints the result as follows:
2014-07-10 11:02:54,619 DEBUG com.netflix.eureka.sampleeurekaclient:69 [main] [Sendrequesttoserviceusingeureka] Nextserverinfo.getappgroupname ()-unknown
2014-07-10 11:02:54,619 DEBUG com.netflix.eureka.sampleeurekaclient:70 [main] [Sendrequesttoserviceusingeureka] Nextserverinfo.getappname ()-sampleservice
2014-07-10 11:02:54,619 DEBUG com.netflix.eureka.sampleeurekaclient:71 [main] [Sendrequesttoserviceusingeureka] Nextserverinfo.getasgname ()-null
2014-07-10 11:02:54,619 DEBUG com.netflix.eureka.sampleeurekaclient:72 [main] [Sendrequesttoserviceusingeureka] Nextserverinfo.gethomepageurl ()-http://defonds-win7:1935/
2014-07-10 11:02:54,620 DEBUG com.netflix.eureka.sampleeurekaclient:73 [main] [Sendrequesttoserviceusingeureka] Nextserverinfo.gethostname ()-defonds-win7
2014-07-10 11:02:54,620 DEBUG com.netflix.eureka.sampleeurekaclient:74 [main] [Sendrequesttoserviceusingeureka] Nextserverinfo.getid ()-defonds-win7
2014-07-10 11:02:54,620 DEBUG com.netflix.eureka.sampleeurekaclient:75 [main] [Sendrequesttoserviceusingeureka] NEXTSERVERINFO.GETIPADDR ( -172.21.40.134)
2014-07-10 11:02:54,620 DEBUG com.netflix.eureka.sampleeurekaclient:76 [main] [Sendrequesttoserviceusingeureka] Nextserverinfo.getlastupdatedtimestamp ()-1404961202884
2014-07-10 11:02:54,620 DEBUG com.netflix.eureka.sampleeurekaclient:77 [main] [Sendrequesttoserviceusingeureka] Nextserverinfo.getport ()-1935
2014-07-10 11:02:54,620 DEBUG com.netflix.eureka.sampleeurekaclient:78 [main] [Sendrequesttoserviceusingeureka] Nextserverinfo.getsecurevipaddress ()-null
2014-07-10 11:02:54,620 DEBUG com.netflix.eureka.sampleeurekaclient:79 [main] [Sendrequesttoserviceusingeureka] Nextserverinfo.getstatuspageurl ()-http://defonds-win7:1935/status
2014-07-10 11:02:54,620 DEBUG com.netflix.eureka.sampleeurekaclient:80 [main] [Sendrequesttoserviceusingeureka] Nextserverinfo.getvipaddress ()-sampleservice.mydomain.net
2014-07-10 11:02:54,620 DEBUG com.netflix.eureka.sampleeurekaclient:81 [main] [Sendrequesttoserviceusingeureka] Nextserverinfo.getlastdirtytimestamp ()-1404961230856
2014-07-10 11:02:54,620 DEBUG com.netflix.eureka.sampleeurekaclient:82 [main] [Sendrequesttoserviceusingeureka] Nextserverinfo.gethealthcheckurls ()-[http://defonds-win7:1935/healthcheck]
2014-07-10 11:02:54,621 DEBUG com.netflix.eureka.sampleeurekaclient:83 [main] [Sendrequesttoserviceusingeureka] Nextserverinfo.getstatus ()-up
All of this information ishttp://serverIP:8080/eureka/v2/apps/Each of the properties of the Sampleservice instance that is displayed corresponds to one by one.
References
    • Https://github.com/Netflix/eureka/tree/master/eureka-server/conf

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.