Skip to content

Getting Started

allenxwang edited this page Jan 25, 2013 · 12 revisions

The simplest way to get started is to use the property driven factory to create instance of client with load balancer. The sample application in ribbon-httpclient shows the basic usage and is described below:

The properties file (sample-client.properties)


# Max number of retries on the same server (excluding the first try)
sample-client.ribbon.MaxAutoRetries=1

# Max number of next servers to retry (excluding the first server)
sample-client.ribbon.MaxAutoRetriesNextServer=1

# Whether all operations can be retried for this client
sample-client.ribbon.OkToRetryOnAllOperations=true

# Interval to refresh the server list from the source
sample-client.ribbon.ServerListRefreshInterval=2000

# Connect timeout used by Apache HttpClient
sample-client.ribbon.ConnectTimeout=3000

# Read timeout used by Apache HttpClient
sample-client.ribbon.ReadTimeout=3000

# Initial list of servers, can be changed via Archaius dynamic property at runtime
sample-client.ribbon.listOfServers=www.microsoft.com:80,www.yahoo.com:80,www.google.com:80

The format of the entry is


<clientName>.<nameSpace>.<propertyName>=<value>

The clientName will be used later in the factory to create client. The nameSpace is configurable and is by default “ribbon”. The common property name is available in CommonClientConfigKey.

The properties can be also defined as system properties, or in any property source loaded by Archaius.

The code

public static void main(String[] args) throws Exception {
      ConfigurationManager.loadPropertiesFromResources("sample-client.properties");  // 1
      System.out.println(ConfigurationManager.getConfigInstance().getProperty("sample-client.ribbon.listOfServers"));
      RestClient client = (RestClient) ClientFactory.getNamedClient("sample-client");  // 2
      HttpClientRequest request = HttpClientRequest.newBuilder().setUri(new URI("/")).build(); // 3
      for (int i = 0; i < 20; i++)  {
      	HttpClientResponse response = client.executeWithLoadBalancer(request); // 4
      	System.out.println("Status code for " + response.getRequestedURI() + "  :" + response.getStatus());
      }
      ZoneAwareLoadBalancer lb = (ZoneAwareLoadBalancer) client.getLoadBalancer();
      System.out.println(lb.getLoadBalancerStats());
      ConfigurationManager.getConfigInstance().setProperty(
      		"sample-client.ribbon.listOfServers", "www.linkedin.com:80,www.google.com:80"); // 5
      System.out.println("changing servers ...");
      Thread.sleep(3000); // 6
      for (int i = 0; i < 20; i++)  {
      	HttpClientResponse response = client.executeWithLoadBalancer(request);
      	System.out.println("Status code for " + response.getRequestedURI() + "  : " + response.getStatus());
      }
      System.out.println(lb.getLoadBalancerStats()); // 7
}

Notes:

  1. Load the properties file using Archaius ConfigurationManager.