From commits-return-1683-apmail-helix-commits-archive=helix.apache.org@helix.apache.org Tue May 7 03:13:59 2013 Return-Path: X-Original-To: apmail-helix-commits-archive@minotaur.apache.org Delivered-To: apmail-helix-commits-archive@minotaur.apache.org Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by minotaur.apache.org (Postfix) with SMTP id 48330FE41 for ; Tue, 7 May 2013 03:13:59 +0000 (UTC) Received: (qmail 80899 invoked by uid 500); 7 May 2013 03:13:58 -0000 Delivered-To: apmail-helix-commits-archive@helix.apache.org Received: (qmail 80861 invoked by uid 500); 7 May 2013 03:13:58 -0000 Mailing-List: contact commits-help@helix.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: dev@helix.apache.org Delivered-To: mailing list commits@helix.apache.org Received: (qmail 80836 invoked by uid 99); 7 May 2013 03:13:58 -0000 Received: from nike.apache.org (HELO nike.apache.org) (192.87.106.230) by apache.org (qpsmtpd/0.29) with ESMTP; Tue, 07 May 2013 03:13:58 +0000 X-ASF-Spam-Status: No, hits=-2000.0 required=5.0 tests=ALL_TRUSTED X-Spam-Check-By: apache.org Received: from [140.211.11.4] (HELO eris.apache.org) (140.211.11.4) by apache.org (qpsmtpd/0.29) with ESMTP; Tue, 07 May 2013 03:13:35 +0000 Received: from eris.apache.org (localhost [127.0.0.1]) by eris.apache.org (Postfix) with ESMTP id 5BDCE2388C6C; Tue, 7 May 2013 03:12:05 +0000 (UTC) Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: svn commit: r1479756 [36/39] - in /incubator/helix/site-content: ./ apidocs/reference/org/apache/helix/ apidocs/reference/org/apache/helix/agent/ apidocs/reference/org/apache/helix/manager/zk/ apidocs/reference/org/apache/helix/messaging/handling/ apid... Date: Tue, 07 May 2013 03:11:00 -0000 To: commits@helix.incubator.apache.org From: kishoreg@apache.org X-Mailer: svnmailer-1.0.8-patched Message-Id: <20130507031205.5BDCE2388C6C@eris.apache.org> X-Virus-Checked: Checked by ClamAV on apache.org Modified: incubator/helix/site-content/xref/org/apache/helix/servicediscovery/ServiceDiscovery.html URL: http://svn.apache.org/viewvc/incubator/helix/site-content/xref/org/apache/helix/servicediscovery/ServiceDiscovery.html?rev=1479756&r1=1479755&r2=1479756&view=diff ============================================================================== --- incubator/helix/site-content/xref/org/apache/helix/servicediscovery/ServiceDiscovery.html (original) +++ incubator/helix/site-content/xref/org/apache/helix/servicediscovery/ServiceDiscovery.html Tue May 7 03:10:53 2013 @@ -9,208 +9,226 @@
 
 1   package org.apache.helix.servicediscovery;
-2   
-3   import java.util.ArrayList;
-4   import java.util.Collections;
-5   import java.util.Date;
-6   import java.util.HashMap;
-7   import java.util.List;
-8   import java.util.Map;
-9   import java.util.Timer;
-10  import java.util.TimerTask;
-11  
-12  import org.apache.helix.HelixDataAccessor;
-13  import org.apache.helix.HelixManager;
-14  import org.apache.helix.HelixManagerFactory;
-15  import org.apache.helix.InstanceType;
-16  import org.apache.helix.LiveInstanceChangeListener;
-17  import org.apache.helix.LiveInstanceInfoProvider;
-18  import org.apache.helix.NotificationContext;
-19  import org.apache.helix.PropertyKey;
-20  import org.apache.helix.PropertyKey.Builder;
-21  import org.apache.helix.ZNRecord;
-22  import org.apache.helix.manager.zk.ZKHelixManager;
-23  import org.apache.helix.model.HelixConfigScope;
-24  import org.apache.helix.model.HelixConfigScope.ConfigScopeProperty;
-25  import org.apache.helix.model.LiveInstance;
-26  import org.apache.helix.model.builder.HelixConfigScopeBuilder;
-27  
-28  public class ServiceDiscovery
-29  {
-30    private final String zkAddress;
-31    private final String cluster;
-32    private HelixManager admin;
-33    List<ServiceMetadata> cache;
-34    static int DEFAULT_POLL_INTERVAL = 30 * 1000; // in ms
-35    private final Mode mode;
-36    Map<String, HelixManager> serviceMap;
-37    private Timer timer;
-38  
-39    enum Mode
-40    {
-41      NONE, // No monitoring, only registration, on demand reading zk
-42      WATCH, // Watches ZK path
-43      POLL// Polls zk at some intervals
-44    }
+2   /*
+3    * Licensed to the Apache Software Foundation (ASF) under one
+4    * or more contributor license agreements.  See the NOTICE file
+5    * distributed with this work for additional information
+6    * regarding copyright ownership.  The ASF licenses this file
+7    * to you under the Apache License, Version 2.0 (the
+8    * "License"); you may not use this file except in compliance
+9    * with the License.  You may obtain a copy of the License at
+10   *
+11   *   http://www.apache.org/licenses/LICENSE-2.0
+12   *
+13   * Unless required by applicable law or agreed to in writing,
+14   * software distributed under the License is distributed on an
+15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+16   * KIND, either express or implied.  See the License for the
+17   * specific language governing permissions and limitations
+18   * under the License.
+19   */
+20  
+21  import java.util.ArrayList;
+22  import java.util.Collections;
+23  import java.util.Date;
+24  import java.util.HashMap;
+25  import java.util.List;
+26  import java.util.Map;
+27  import java.util.Timer;
+28  import java.util.TimerTask;
+29  
+30  import org.apache.helix.HelixDataAccessor;
+31  import org.apache.helix.HelixManager;
+32  import org.apache.helix.HelixManagerFactory;
+33  import org.apache.helix.InstanceType;
+34  import org.apache.helix.LiveInstanceChangeListener;
+35  import org.apache.helix.LiveInstanceInfoProvider;
+36  import org.apache.helix.NotificationContext;
+37  import org.apache.helix.PropertyKey;
+38  import org.apache.helix.PropertyKey.Builder;
+39  import org.apache.helix.ZNRecord;
+40  import org.apache.helix.manager.zk.ZKHelixManager;
+41  import org.apache.helix.model.HelixConfigScope;
+42  import org.apache.helix.model.HelixConfigScope.ConfigScopeProperty;
+43  import org.apache.helix.model.LiveInstance;
+44  import org.apache.helix.model.builder.HelixConfigScopeBuilder;
 45  
-46    public ServiceDiscovery(String zkAddress, String cluster, Mode mode)
-47    {
-48      this.zkAddress = zkAddress;
-49      this.cluster = cluster;
-50      this.mode = mode;
-51      serviceMap = new HashMap<String, HelixManager>();
-52      cache = Collections.emptyList();
-53    }
-54  
-55    /**
-56     * 
-57     * @return returns true if
-58     */
-59    public boolean start() throws Exception
-60    {
-61      // auto create cluster and allow nodes to automatically join the cluster
-62      admin = HelixManagerFactory.getZKHelixManager(cluster, "service-discovery",
-63          InstanceType.ADMINISTRATOR, zkAddress);
-64      admin.connect();
-65      admin.getClusterManagmentTool().addCluster(cluster, false);
-66      HelixConfigScope scope = new HelixConfigScopeBuilder(
-67          ConfigScopeProperty.CLUSTER).forCluster(cluster).build();
-68  
-69      Map<String, String> properties = new HashMap<String, String>();
-70      properties.put(ZKHelixManager.ALLOW_PARTICIPANT_AUTO_JOIN,
-71          String.valueOf(true));
-72      admin.getClusterManagmentTool().setConfig(scope, properties);
-73      switch (mode)
-74      {
-75      case POLL:
-76        startBackgroundTask();
-77        break;
-78      case WATCH:
-79        setupWatcher();
-80        break;
-81      case NONE:// dont monitor changes, supports only registration
-82  
-83      }
-84      refreshCache();
-85      return true;
-86    }
-87  
-88    private void startBackgroundTask()
-89    {
-90      TimerTask timertask = new TimerTask()
-91      {
-92  
-93        @Override
-94        public void run()
-95        {
-96          refreshCache();
-97        }
-98      };
-99      timer = new Timer();
-100     timer.scheduleAtFixedRate(timertask, DEFAULT_POLL_INTERVAL, DEFAULT_POLL_INTERVAL);
-101   }
-102 
-103   private void setupWatcher() throws Exception
-104   {
+46  public class ServiceDiscovery
+47  {
+48    private final String zkAddress;
+49    private final String cluster;
+50    private HelixManager admin;
+51    List<ServiceMetadata> cache;
+52    static int DEFAULT_POLL_INTERVAL = 30 * 1000; // in ms
+53    private final Mode mode;
+54    Map<String, HelixManager> serviceMap;
+55    private Timer timer;
+56  
+57    enum Mode
+58    {
+59      NONE, // No monitoring, only registration, on demand reading zk
+60      WATCH, // Watches ZK path
+61      POLL// Polls zk at some intervals
+62    }
+63  
+64    public ServiceDiscovery(String zkAddress, String cluster, Mode mode)
+65    {
+66      this.zkAddress = zkAddress;
+67      this.cluster = cluster;
+68      this.mode = mode;
+69      serviceMap = new HashMap<String, HelixManager>();
+70      cache = Collections.emptyList();
+71    }
+72  
+73    /**
+74     * 
+75     * @return returns true if
+76     */
+77    public boolean start() throws Exception
+78    {
+79      // auto create cluster and allow nodes to automatically join the cluster
+80      admin = HelixManagerFactory.getZKHelixManager(cluster, "service-discovery",
+81          InstanceType.ADMINISTRATOR, zkAddress);
+82      admin.connect();
+83      admin.getClusterManagmentTool().addCluster(cluster, false);
+84      HelixConfigScope scope = new HelixConfigScopeBuilder(
+85          ConfigScopeProperty.CLUSTER).forCluster(cluster).build();
+86  
+87      Map<String, String> properties = new HashMap<String, String>();
+88      properties.put(ZKHelixManager.ALLOW_PARTICIPANT_AUTO_JOIN,
+89          String.valueOf(true));
+90      admin.getClusterManagmentTool().setConfig(scope, properties);
+91      switch (mode)
+92      {
+93      case POLL:
+94        startBackgroundTask();
+95        break;
+96      case WATCH:
+97        setupWatcher();
+98        break;
+99      case NONE:// dont monitor changes, supports only registration
+100 
+101     }
+102     refreshCache();
+103     return true;
+104   }
 105 
-106     LiveInstanceChangeListener listener = new LiveInstanceChangeListener()
-107     {
-108       @Override
-109       public void onLiveInstanceChange(List<LiveInstance> liveInstances,
-110           NotificationContext changeContext)
-111       {
-112         if(changeContext.getType() != NotificationContext.Type.FINALIZE){
-113           refreshCache();
-114         }
+106   private void startBackgroundTask()
+107   {
+108     TimerTask timertask = new TimerTask()
+109     {
+110 
+111       @Override
+112       public void run()
+113       {
+114         refreshCache();
 115       }
 116     };
-117     admin.addLiveInstanceChangeListener(listener);
-118   }
-119 
-120   public boolean stop()
-121   {
-122     if (admin != null && admin.isConnected())
-123     {
-124       admin.disconnect();
-125     }
-126     if (timer != null)
-127     {
-128       timer.cancel();
-129     }
-130     return true;
-131   }
-132 
-133   public void deregister(final String serviceId)
-134   {
-135     HelixManager helixManager = serviceMap.get(serviceId);
-136     if (helixManager != null && helixManager.isConnected())
-137     {
-138       helixManager.disconnect();
-139     }
-140   }
-141 
-142   public boolean register(final String serviceId,
-143       final ServiceMetadata serviceMetadata) throws Exception
-144   {
-145     HelixManager helixManager = HelixManagerFactory.getZKHelixManager(cluster,
-146         serviceId, InstanceType.PARTICIPANT, zkAddress);
-147     LiveInstanceInfoProvider liveInstanceInfoProvider = new LiveInstanceInfoProvider()
-148     {
-149       @Override
-150       public ZNRecord getAdditionalLiveInstanceInfo()
-151       {
-152         // serialize serviceMetadata to ZNRecord
-153         ZNRecord rec = new ZNRecord(serviceId);
-154         rec.setSimpleField("HOST", serviceMetadata.getHost());
-155         rec.setSimpleField("PORT", String.valueOf(serviceMetadata.getPort()));
-156         rec.setSimpleField("SERVICE_NAME", serviceMetadata.getServiceName());
-157         return rec;
-158       }
-159     };
-160     helixManager.setLiveInstanceInfoProvider(liveInstanceInfoProvider);
-161     helixManager.connect();
-162     serviceMap.put(serviceId, helixManager);
-163     refreshCache();
-164     return true;
-165   }
-166 
-167   private void refreshCache()
-168   {
-169     Builder propertyKeyBuilder = new PropertyKey.Builder(cluster);
-170     HelixDataAccessor helixDataAccessor = admin.getHelixDataAccessor();
-171     List<LiveInstance> liveInstances = helixDataAccessor
-172         .getChildValues(propertyKeyBuilder.liveInstances());
-173     refreshCache(liveInstances);
-174   }
-175 
-176   private void refreshCache(List<LiveInstance> liveInstances)
-177   {
-178     List<ServiceMetadata> services = new ArrayList<ServiceMetadata>();
-179     for (LiveInstance liveInstance : liveInstances)
-180     {
-181       ServiceMetadata metadata = new ServiceMetadata();
-182       ZNRecord rec = liveInstance.getRecord();
-183       metadata.setPort(Integer.parseInt(rec.getSimpleField("PORT")));
-184       metadata.setHost(rec.getSimpleField("HOST"));
-185       metadata.setServiceName(rec.getSimpleField("SERVICE_NAME"));
-186       services.add(metadata);
-187     }
-188     //protect against multiple threads updating this
-189     synchronized (this)
-190     {
-191       cache = services;
-192     }
-193   }
-194 
-195   public List<ServiceMetadata> findAllServices()
-196   {
-197     if (mode == Mode.NONE)
+117     timer = new Timer();
+118     timer.scheduleAtFixedRate(timertask, DEFAULT_POLL_INTERVAL, DEFAULT_POLL_INTERVAL);
+119   }
+120 
+121   private void setupWatcher() throws Exception
+122   {
+123 
+124     LiveInstanceChangeListener listener = new LiveInstanceChangeListener()
+125     {
+126       @Override
+127       public void onLiveInstanceChange(List<LiveInstance> liveInstances,
+128           NotificationContext changeContext)
+129       {
+130         if(changeContext.getType() != NotificationContext.Type.FINALIZE){
+131           refreshCache();
+132         }
+133       }
+134     };
+135     admin.addLiveInstanceChangeListener(listener);
+136   }
+137 
+138   public boolean stop()
+139   {
+140     if (admin != null && admin.isConnected())
+141     {
+142       admin.disconnect();
+143     }
+144     if (timer != null)
+145     {
+146       timer.cancel();
+147     }
+148     return true;
+149   }
+150 
+151   public void deregister(final String serviceId)
+152   {
+153     HelixManager helixManager = serviceMap.get(serviceId);
+154     if (helixManager != null && helixManager.isConnected())
+155     {
+156       helixManager.disconnect();
+157     }
+158   }
+159 
+160   public boolean register(final String serviceId,
+161       final ServiceMetadata serviceMetadata) throws Exception
+162   {
+163     HelixManager helixManager = HelixManagerFactory.getZKHelixManager(cluster,
+164         serviceId, InstanceType.PARTICIPANT, zkAddress);
+165     LiveInstanceInfoProvider liveInstanceInfoProvider = new LiveInstanceInfoProvider()
+166     {
+167       @Override
+168       public ZNRecord getAdditionalLiveInstanceInfo()
+169       {
+170         // serialize serviceMetadata to ZNRecord
+171         ZNRecord rec = new ZNRecord(serviceId);
+172         rec.setSimpleField("HOST", serviceMetadata.getHost());
+173         rec.setSimpleField("PORT", String.valueOf(serviceMetadata.getPort()));
+174         rec.setSimpleField("SERVICE_NAME", serviceMetadata.getServiceName());
+175         return rec;
+176       }
+177     };
+178     helixManager.setLiveInstanceInfoProvider(liveInstanceInfoProvider);
+179     helixManager.connect();
+180     serviceMap.put(serviceId, helixManager);
+181     refreshCache();
+182     return true;
+183   }
+184 
+185   private void refreshCache()
+186   {
+187     Builder propertyKeyBuilder = new PropertyKey.Builder(cluster);
+188     HelixDataAccessor helixDataAccessor = admin.getHelixDataAccessor();
+189     List<LiveInstance> liveInstances = helixDataAccessor
+190         .getChildValues(propertyKeyBuilder.liveInstances());
+191     refreshCache(liveInstances);
+192   }
+193 
+194   private void refreshCache(List<LiveInstance> liveInstances)
+195   {
+196     List<ServiceMetadata> services = new ArrayList<ServiceMetadata>();
+197     for (LiveInstance liveInstance : liveInstances)
 198     {
-199       refreshCache();
-200     }
-201     return cache;
-202   }
-203 }
+199       ServiceMetadata metadata = new ServiceMetadata();
+200       ZNRecord rec = liveInstance.getRecord();
+201       metadata.setPort(Integer.parseInt(rec.getSimpleField("PORT")));
+202       metadata.setHost(rec.getSimpleField("HOST"));
+203       metadata.setServiceName(rec.getSimpleField("SERVICE_NAME"));
+204       services.add(metadata);
+205     }
+206     //protect against multiple threads updating this
+207     synchronized (this)
+208     {
+209       cache = services;
+210     }
+211   }
+212 
+213   public List<ServiceMetadata> findAllServices()
+214   {
+215     if (mode == Mode.NONE)
+216     {
+217       refreshCache();
+218     }
+219     return cache;
+220   }
+221 }
 

Modified: incubator/helix/site-content/xref/org/apache/helix/servicediscovery/ServiceDiscoveryDemo.html URL: http://svn.apache.org/viewvc/incubator/helix/site-content/xref/org/apache/helix/servicediscovery/ServiceDiscoveryDemo.html?rev=1479756&r1=1479755&r2=1479756&view=diff ============================================================================== --- incubator/helix/site-content/xref/org/apache/helix/servicediscovery/ServiceDiscoveryDemo.html (original) +++ incubator/helix/site-content/xref/org/apache/helix/servicediscovery/ServiceDiscoveryDemo.html Tue May 7 03:10:53 2013 @@ -10,119 +10,138 @@ 1 package org.apache.helix.servicediscovery; 2 -3 import java.net.InetAddress; -4 import java.net.UnknownHostException; -5 import java.util.ArrayList; -6 import java.util.List; -7 -8 import org.apache.helix.servicediscovery.ServiceDiscovery.Mode; -9 -10 public class ServiceDiscoveryDemo -11 { -12 public static void main(String[] args) throws Exception -13 { -14 -15 String clusterName = "service-discovery-demo"; -16 String zkAddress = "localhost:2199"; -17 String serviceName = "myServiceName"; -18 int numServices = 5; -19 -20 //registration + zk watch -21 demo(clusterName, zkAddress, serviceName, numServices, Mode.WATCH); -22 //registration + periodic poll -23 demo(clusterName, zkAddress, serviceName, numServices, Mode.POLL); -24 //only registration + ondemand -25 demo(clusterName, zkAddress, serviceName, numServices, Mode.NONE); +3 /* +4 * Licensed to the Apache Software Foundation (ASF) under one +5 * or more contributor license agreements. See the NOTICE file +6 * distributed with this work for additional information +7 * regarding copyright ownership. The ASF licenses this file +8 * to you under the Apache License, Version 2.0 (the +9 * "License"); you may not use this file except in compliance +10 * with the License. You may obtain a copy of the License at +11 * +12 * http://www.apache.org/licenses/LICENSE-2.0 +13 * +14 * Unless required by applicable law or agreed to in writing, +15 * software distributed under the License is distributed on an +16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +17 * KIND, either express or implied. See the License for the +18 * specific language governing permissions and limitations +19 * under the License. +20 */ +21 +22 import java.net.InetAddress; +23 import java.net.UnknownHostException; +24 import java.util.ArrayList; +25 import java.util.List; 26 -27 } +27 import org.apache.helix.servicediscovery.ServiceDiscovery.Mode; 28 -29 private static void demo(String clusterName, String zkAddress, -30 String serviceName, int numServices, Mode mode) throws Exception, -31 UnknownHostException +29 public class ServiceDiscoveryDemo +30 { +31 public static void main(String[] args) throws Exception 32 { -33 System.out.println("START:Service discovery demo mode:"+ mode); -34 ServiceDiscovery serviceDiscovery = new ServiceDiscovery(zkAddress, -35 clusterName, mode); -36 serviceDiscovery.start(); -37 int startPort = 12000; -38 List<MyService> serviceList = new ArrayList<MyService>(); -39 System.out.println("\tRegistering service"); -40 for (int i = 0; i < numServices; i++) -41 { -42 String host = InetAddress.getLocalHost().getHostName(); -43 int port = startPort + i; -44 String serviceId = host + "_" + port; -45 ServiceMetadata metadata = new ServiceMetadata(); -46 metadata.setHost(host); -47 metadata.setPort(port); -48 metadata.setServiceName(serviceName); -49 MyService service = new MyService(serviceId, metadata, serviceDiscovery); -50 service.start(); -51 serviceList.add(service); -52 System.out.println("\t\t"+serviceId); -53 } -54 listAvailableServices(serviceDiscovery); -55 stopAndStartServices(serviceDiscovery, serviceList, mode); -56 -57 for (MyService service : serviceList) -58 { -59 serviceDiscovery.deregister(service.getServiceId()); -60 } -61 serviceDiscovery.stop(); -62 System.out.println("END:Service discovery demo mode:"+ mode); -63 System.out.println("============================================="); -64 } -65 -66 /** -67 * Randomly stop and start some services, list all the available services. -68 * This demonstrates that the list is dynamically updated when services -69 * starts/stops -70 * -71 * @param serviceDiscovery -72 * @param serviceList -73 * @param mode -74 * @throws Exception -75 */ -76 private static void stopAndStartServices(ServiceDiscovery serviceDiscovery, -77 List<MyService> serviceList, Mode mode) throws Exception -78 { -79 // randomly select some services stop -80 int index = ((int) (Math.random() * 1000)) % serviceList.size(); -81 MyService service = serviceList.get(index); -82 String serviceId = service.getServiceId(); -83 System.out.println("\tDeregistering service:\n\t\t" + serviceId); -84 serviceDiscovery.deregister(serviceId); -85 switch (mode) -86 { -87 case WATCH: -88 Thread.sleep(100);// callback should be immediate -89 break; -90 case POLL: -91 System.out.println("\tSleeping for poll interval:" + ServiceDiscovery.DEFAULT_POLL_INTERVAL); -92 Thread.sleep(ServiceDiscovery.DEFAULT_POLL_INTERVAL + 1000); -93 break; -94 case NONE: // no need to wait, it reads on demand -95 default: -96 break; -97 } -98 listAvailableServices(serviceDiscovery); -99 Thread.sleep(100); -100 System.out.println("\tRegistering service:" + serviceId); -101 serviceDiscovery.register(serviceId, service.getMetadata()); -102 } -103 -104 private static void listAvailableServices(ServiceDiscovery serviceDiscovery) -105 { -106 List<ServiceMetadata> findAllServices = serviceDiscovery.findAllServices(); -107 System.out.println("\tSERVICES AVAILABLE"); -108 System.out.printf("\t\t%s \t%s \t\t\t%s\n", "SERVICENAME", "HOST", "PORT"); -109 for (ServiceMetadata serviceMetadata : findAllServices) -110 { -111 System.out.printf("\t\t%s \t%s \t\t%s\n", serviceMetadata.getServiceName(), -112 serviceMetadata.getHost(), serviceMetadata.getPort()); -113 } -114 } -115 } +33 +34 String clusterName = "service-discovery-demo"; +35 String zkAddress = "localhost:2199"; +36 String serviceName = "myServiceName"; +37 int numServices = 5; +38 +39 //registration + zk watch +40 demo(clusterName, zkAddress, serviceName, numServices, Mode.WATCH); +41 //registration + periodic poll +42 demo(clusterName, zkAddress, serviceName, numServices, Mode.POLL); +43 //only registration + ondemand +44 demo(clusterName, zkAddress, serviceName, numServices, Mode.NONE); +45 +46 } +47 +48 private static void demo(String clusterName, String zkAddress, +49 String serviceName, int numServices, Mode mode) throws Exception, +50 UnknownHostException +51 { +52 System.out.println("START:Service discovery demo mode:"+ mode); +53 ServiceDiscovery serviceDiscovery = new ServiceDiscovery(zkAddress, +54 clusterName, mode); +55 serviceDiscovery.start(); +56 int startPort = 12000; +57 List<MyService> serviceList = new ArrayList<MyService>(); +58 System.out.println("\tRegistering service"); +59 for (int i = 0; i < numServices; i++) +60 { +61 String host = InetAddress.getLocalHost().getHostName(); +62 int port = startPort + i; +63 String serviceId = host + "_" + port; +64 ServiceMetadata metadata = new ServiceMetadata(); +65 metadata.setHost(host); +66 metadata.setPort(port); +67 metadata.setServiceName(serviceName); +68 MyService service = new MyService(serviceId, metadata, serviceDiscovery); +69 service.start(); +70 serviceList.add(service); +71 System.out.println("\t\t"+serviceId); +72 } +73 listAvailableServices(serviceDiscovery); +74 stopAndStartServices(serviceDiscovery, serviceList, mode); +75 +76 for (MyService service : serviceList) +77 { +78 serviceDiscovery.deregister(service.getServiceId()); +79 } +80 serviceDiscovery.stop(); +81 System.out.println("END:Service discovery demo mode:"+ mode); +82 System.out.println("============================================="); +83 } +84 +85 /** +86 * Randomly stop and start some services, list all the available services. +87 * This demonstrates that the list is dynamically updated when services +88 * starts/stops +89 * +90 * @param serviceDiscovery +91 * @param serviceList +92 * @param mode +93 * @throws Exception +94 */ +95 private static void stopAndStartServices(ServiceDiscovery serviceDiscovery, +96 List<MyService> serviceList, Mode mode) throws Exception +97 { +98 // randomly select some services stop +99 int index = ((int) (Math.random() * 1000)) % serviceList.size(); +100 MyService service = serviceList.get(index); +101 String serviceId = service.getServiceId(); +102 System.out.println("\tDeregistering service:\n\t\t" + serviceId); +103 serviceDiscovery.deregister(serviceId); +104 switch (mode) +105 { +106 case WATCH: +107 Thread.sleep(100);// callback should be immediate +108 break; +109 case POLL: +110 System.out.println("\tSleeping for poll interval:" + ServiceDiscovery.DEFAULT_POLL_INTERVAL); +111 Thread.sleep(ServiceDiscovery.DEFAULT_POLL_INTERVAL + 1000); +112 break; +113 case NONE: // no need to wait, it reads on demand +114 default: +115 break; +116 } +117 listAvailableServices(serviceDiscovery); +118 Thread.sleep(100); +119 System.out.println("\tRegistering service:" + serviceId); +120 serviceDiscovery.register(serviceId, service.getMetadata()); +121 } +122 +123 private static void listAvailableServices(ServiceDiscovery serviceDiscovery) +124 { +125 List<ServiceMetadata> findAllServices = serviceDiscovery.findAllServices(); +126 System.out.println("\tSERVICES AVAILABLE"); +127 System.out.printf("\t\t%s \t%s \t\t\t%s\n", "SERVICENAME", "HOST", "PORT"); +128 for (ServiceMetadata serviceMetadata : findAllServices) +129 { +130 System.out.printf("\t\t%s \t%s \t\t%s\n", serviceMetadata.getServiceName(), +131 serviceMetadata.getHost(), serviceMetadata.getPort()); +132 } +133 } +134 }