Official Spring Cloud documentation-Client Server Load balancer: Ribbon, cloudribbon

Source: Internet
Author: User
Tags new set

Official Spring Cloud documentation-Client Server Load balancer: Ribbon, cloudribbon

Official documentation: http://cloud.spring.io/spring-cloud-static/Dalston.SR2/#_spring_cloud_netflix

In this article, I did some tests in: http://git.oschina.net/dreamingodd/spring-cloud-preparation

 

Client Side Load Balancer: Ribbon Client Load balancing: Ribbon

Ribbon is a client side load balancer which gives you a lot of control over the behaviour of HTTP and TCP clients. feign already uses Ribbon, so if you are using @ FeignClient then this section also applies.

Ribbon is a Client Load balancer that provides developers with a lot of control over HTTP and TCP client behavior. Feigh is already using Ribbon, so this section still applies if developers use @ FeignClient.

A central concept in Ribbon is that of the named client. each load balancer is part of an ensemble of components that work together to contact a remote server on demand, and the ensemble has a name that you give it as an application developer (e.g. using the @ FeignClient annotation ). spring Cloud creates a new ensemble as an ApplicationContext on demand for each named client using RibbonClientConfiguration. this contains (amongst other things) an ILoadBalancer, a RestClient, and a ServerListFilter.

The core concept of Ribbon is the named client. Each Server Load balancer is part of a component combination. It works together to communicate with the remote server as needed. developers can name the combination (for example, using the @ FeignClient annotation ). Spring Cloud uses RibbonClientConfiguration to create a new set for each named client as needed as the application context ). The set includes ILoadBalancer, RestClient, and ServerListFilter (of course there are other unlisted ones ).

How to Include Ribbon

To include Ribbon in your project use the starter with group org. springframework. cloud and artifact id spring-cloud-starter-ribbon. see the Spring Cloud Project page for details on setting up your build system with the current Spring Cloud Release Train.

Introduce the spring-cloud-starter-ribbon Project of org. springframework. cloud. For details, see Spring Cloud Project page.

Customizing the Ribbon Client

You can configure some bits of a Ribbon client using external properties in <client>. ribbon. *, which is no different than using the Netflix APIs natively, doesn't that you can use Spring Boot configuration files. the native options can be inspected as static fields in CommonClientConfigKey (part of ribbon-core ).

Developers can use the <client>. ribbon. * external configuration to enable the Ribbon function. In addition to using the Spring Boot configuration file, this method is no different from using the native nextoffapis. Native options can be seen in CommonClientConfigKey constants (part of ribbon-core ).

Spring Cloud also lets you take full control of the client by declaring additional configuration (on top of the RibbonClientConfiguration) using @ RibbonClient. Example:

Spring Cloud also allows developers to declare additional configurations (above RibbonClientConfiguration)-@ RibbonClient to gain full control of the client. For example:

@Configuration @RibbonClient(name = "foo", configuration = FooConfiguration.class)
public class TestConfiguration {
}

In this case the client is composed from the components already in RibbonClientConfiguration together with any in FooConfiguration (where the latter generally will override the former ).

In this example, the client is composed of Components in RibbonClientConfiguration and any components in FooConfiguration (the latter usually overwrites the former ).

WARNINGThe FooConfiguration has to be @ Configuration but take care that it is not in a @ ComponentScan for the main application context, otherwise it will be shared by all the @ RibbonClients. if you use @ ComponentScan (or @ SpringBootApplication) you need to take steps to avoid it being stored ded (for instance put it in a separate, non-overlapping package, or specify the packages to scan explicitly in the @ ComponentScan ).

WarningFooConfiguration must have @ Configuration, but note that it is not in the @ ComponentScan of the main application context. Otherwise, it will be shared by all @ RibbonClients (that is, the default value of all clients is overwritten ). If developers use @ ComponentScan (or @ SpringBootApplication), they must take measures to avoid being overwritten (for example, placing it in an independent, non-overlapping package, or use @ ComponentScan to specify the package to be scanned.

Spring Cloud Netflix provides the following beans by default for ribbon (BeanType beanName: ClassName ):

By default, Spring Cloud Netflix provides the following bean (BeanType beanName: ClassName) for Ribbon ):

  • IClientConfig ribbonClientConfig: DefaultClientConfigImpl
  • IRule ribbonRule: ZoneAvoidanceRule
  • IPing ribbonPing: NoOpPing
  • ServerList <Server> ribbonServerList: ConfigurationBasedServerList
  • ServerListFilter <Server> ribbonServerListFilter: ZonePreferenceServerListFilter
  • ILoadBalancer ribbonLoadBalancer: ZoneAwareLoadBalancer
  • ServerListUpdater ribbonServerListUpdater: PollingServerListUpdater

Creating a bean of one of those type and placing it in a @ RibbonClient configuration (such as FooConfiguration above) allows you to override each one of the beans described. Example:

Create one of the above beans and add it to the @ RibbonClient configuration (which can be the FooConfiguration above) to overwrite the default Bean. For example:

@Configuration public class FooConfiguration { @Bean public IPing ribbonPing(IClientConfig config) { return new PingUrl();
    }
}

This replaces the NoOpPing with PingUrl.

The above @ Bean overwrites NoOpPing with PingUrl.

Customizing the Ribbon Client using properties use properties to customize the Ribbon Client

Starting with version 1.2.0, Spring Cloud Netflix now supports customizing Ribbon clients using properties to be compatible with the Ribbon documentation.

Starting from 1.2.0, Spring Cloud Netflix supports and is compatible with custom Ribbon clients. For details, see Ribbon documentation.

This allows you to change behavior at start up time in different environments.

In this way, developers can change client behavior according to different environments at startup.

The supported properties are listed below and shocould be prefixed by <clientName>. ribbon .:

<ClientName>. ribbon. prefix is the property configuration supported by Ribbon.

  • NFLoadBalancerClassName: shocould implement ILoadBalancer
  • NFLoadBalancerRuleClassName: shocould implement IRule
  • NFLoadBalancerPingClassName: shocould implement IPing
  • NIWSServerListClassName: shocould implement ServerList
  • NIWSServerListFilterClassName shold implement ServerListFilter

NOTEClasses defined in these properties have precedence over beans defined using @ RibbonClient (configuration = MyRibbonConfig. class) and the defaults provided by Spring Cloud Netflix.

Note:These analogy uses the Bean defined by @ RibbonClient (configuration = MyRibbonConfig. class) and the default Bean provided by Spring Cloud Netflix.

To set the IRule for a service name users you coshould set the following:

To set IRule for a service name user, developers can set the following content:

Application. yml

users:  ribbon:    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.WeightedResponseTimeRule

See the Ribbon documentation for implementations provided by Ribbon.

For details about Ribbon implementation, see Ribbon documentation.

Using Ribbon with Eureka and Eureka

When Eureka is used in conjunction with Ribbon (I. e ., both are on the classpath) the ribbonServerList is overridden with an extension of DiscoveryEnabledNIWSServerList which populates the list of servers from Eureka. it also replaces the IPing interface with NIWSDiscoveryPing which delegates to Eureka to determine if a server is up. the ServerList that is installed by default is a DomainExtractingServerList and the purpose of this is to make physical metadata available to the load balancer without using aws ami metadata (which is what Netflix relies on ). by default the server list will be constructed with "zone" information as provided in the instance metadata (so on the remote clients set eureka. instance. metadataMap. zone), and if that is missing it can use the domain name from the server hostname as a proxy for zone (if the flag approximateZoneFromHostname is set ). once the zone information is available it can be used in a ServerListFilter. by default it will be used to locate a server in the same zone as the client because the default is a ZonePreferenceServerListFilter. the zone of the client is determined the same way as the remote instances by default, I. e. via eureka. instance. metadataMap. zone.

When Eureka and Ribbon are used in combination (that is, they are all in classpath), RibbonServerList will be extended to DiscoveryEnabledNIWSServerList, which retrieves and fills in server list information from Eureka cache information. DiscoveryEnabledNIWSServerList also replaces the IPing interface with NIWSDiscoveryPing. NIWSDiscoveryPing entrusts Eureka to check whether the service is started. By default, the installed ServerList is a DomainExtractingServerList, which aims to make the physical metadata available for the Server Load balancer without using aws ami metadata (Netflix depends on this ). The server list is built by default by the "zone" Information provided by the instance metadata. If this information is missing, the domain name of the server host will be used as the proxy for a zone (provided that the approximateZoneFromHostname flag is set ). Once the zone information is determined, ServerListFilter will be used. As long as the default value is ZonePreferenceServerListFilter, it is used to find servers in the same region as the client. By default, the client zone is the same as the remote instance through eureka. instance. metadataMap. zone.

NOTEThe orthodox "archaius" way to set the client zone is via a configuration property called "@ zone ", and Spring Cloud will use that in preference to all other settings if it is available (note that the key will have to be quoted in YAML configuration ).

Note:Set the Orthodox "archaius" in the client region by using a Configuration Attribute named "@ zone". If Spring Cloud is available, it will take precedence over all other settings. (Note that this configuration item must be referenced in the YAML configuration ).

NOTEIf there is no other source of zone data then a guess is made based on the client configuration (as opposed to the instance configuration ). we take eureka. client. availabilityZones, which is a map from region name to a list of zones, and pull out the first zone for the instance's own region (I. e. the eureka. client. region, which defaults to "us-east-1" for comatibility with native Netflix ).

Note:If there is no other zone data source, you can guess based on the client configuration (opposite to the instance configuration. client. availabilityZones (ing from region name to region list), and pulls the first zone (eureka) of the Instance's region. client. region. The default value is "us-east-1" to ensure compatibility with native Netflix ).

Example: How to Use Ribbon Without Eureka How to Use Ribbon independently

Eureka is a convenient way to abstract the discovery of remote servers so you don't have to hard code their URLs in clients, but if you prefer not to use it, ribbon and Feign are still quite amenable. suppose you have declared a @ RibbonClient for "stores", and Eureka is not in use (and not even on the classpath ). the Ribbon client defaults to a configured server list, and you can supply the configuration like this:

Eureka is a convenient method for discovering abstract remote services. With Eureka, developers do not need to write the URL to death in code. If you want to write the URL to death, it is not impossible, ribbon and Feign are flexible. Assume that you have already declared a @ RibbonClient for "stores" and didn't use Eureka (even in classpath ). The Ribbon client has a default server list that supports the following configurations:

Application. yml

stores:  ribbon:    listOfServers: example.com.google.com
Example: Disable Eureka use in Ribbon to kill Eureka

Setting the property ribbon. eureka. enabled = false will explicitly disable the use of Eureka in Ribbon. Set ribbon. eureka. enabled = false.

Application. yml

ribbon:  eureka:   enabled: false
Using the Ribbon API Directly use the Ribbon API

You can also use the LoadBalancerClient directly. Example:

public class MyClass { @Autowired private LoadBalancerClient loadBalancer; public void doStuff() {
        ServiceInstance instance = loadBalancer.choose("stores");
        URI storesUri = URI.create(String.format("http://%s:%s", instance.getHost(), instance.getPort())); // ... do something with the URI
    }
}
Caching of Ribbon Configuration Cache

Each Ribbon named client has a corresponding child Application Context that Spring Cloud maintains, this application context is lazily loaded up on the first request to the named client. this lazy loading behavior can be changed to instead eagerly load up these child Application contexts at startup by specifying the names of the Ribbon clients.

Spring Cloud maintains the corresponding sub-application context for each named Ribbon client, which is lazy loaded when the client is requested for the first time. However, specifying the names of these Ribbon clients allows them to load at startup. (It is not clear what the client name is)

Application. yml

ribbon:
   eager-load:
     enabled: true
     clients: client1, client2, client3


dreamingodd original article, please indicate the source if reprinted. 


Related Article

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.