Ribbon and Eureka Integration

Source: Internet
Author: User
Ribbon is an open-source Cloud Middle Layer Service Project released by Netflix. Its main function is to provide client-side software Load Balancing algorithms to connect Netflix's middle layer services. Eureka is a restful service used to locate intermediate services running in the AWS domain (region. This article introduces Eureka and ribbon integration, with ribbon custom Server Load balancer algorithm examples.
The integration of ribbon and Eureka actually enables ribbon to act as the application client role in the Eureka architecture. This article is based on the previous blog. Before reading this article, you are advised to refer to cloud intermediate layer service-region aware server Load balancer ribbon and Eureka application client running example.
Why Eureka need ribbon?
Why do I need ribbon when Eureka comes with a client library?
Ribbon's load balancing algorithm and region-aware Load balancer have been tested for a long time and can be used directly.
Why ribbon need Eureka?
Everyone familiar with ribbon knows that ribbon maintains a list of servers. If the server goes down, ribbon can remove the server by itself. However, if the server goes down, restart the server, or Add a new load node. We need to manually call the Ribbon interface to add it to the server list of ribbon dynamically. This is obviously not satisfactory. How can I add a service list when a service node is started? -- Eureka. Eureka provides the application service client's self-registration function. In addition, Eureka's cache mechanism can prevent catastrophic consequences of large-scale downtime.
Next we start integration. Before performing the following operations, make sure that the Eureka server is started and that the Eureka application service client has been registered with the server (see Eureka application client running example).
1. Add the ribbon-Eureka dependency package
Http://mvnrepository.com/artifact/com.netflix.ribbon/ribbon-eureka select the appropriate Version Download, the author download is the ribbon-eureka-0.3.12.jar http://mvnrepository.com/artifact/com.netflix.ribbon/ribbon-eureka/0.3.12.
2. Configuration Initialization

The configuration file uses the Eureka application client configuration in Eureka application client running example. Add the following configuration items:

  • Enable the Client Server Load balancer and configure it as dynamicserverlistloadbalancer or its subclass (this does not need to be reflected in the configuration, because this is the default value of Eureka and ribbon integration is true ).
  • Configure serverlist as com. Netflix. niws. loadbalancer. discoveryenabledniwsserverlist.
  • Configure the server (Server Load balancer node) Refresh frequency (optional. The default value is 30 seconds ).
  • Configure the virtual address (VIP address) of the server for the Eureka client, and ensure that the address matches the one used when the server (Application Service) registers the Eureka server.
In short, the following configuration items are added on the basis of Eureka application client running example:
Myclient. ribbon. niwsserverlistclassname = com. netflix. niws. loadbalancer. discoveryenabledniwsserverlist # refresh every minute myclient. ribbon. serverlistrefreshinterval = 60000 # movieservice is the virtual address that the target server (s) uses to register with Eureka servermyclient. ribbon. the initialization method of deploymentcontextbasedvipsses = movieservice configuration file still adopts the configuration Initialization Method in Eureka application client running example: // register with eurekadiscoverymanager. getinstance (). initcomponent (New mydatacenterinstanceconfig (), new defaulteurekaclientconfig (); applicationinfomanager. getinstance (). setinstancestatus (instancestatus. UP );

3. Custom Server Load balancer Algorithms
Server Load balancer algorithm. For the sake of simple demo, use the random algorithm com. Netflix. loadbalancer. randomrule to get the Server Host:
// get LoadBalancer instance from configuration, properties fileDynamicServerListLoadBalancer lb = (DynamicServerListLoadBalancer) ClientFactory.getNamedLoadBalancer("myclient");// use RandomRule ‘s RandomRule algorithm to get a random server from lb ‘s server listRandomRule randomRule = new RandomRule();Server randomAlgorithmServer = randomRule.choose(lb, null);logger.debug("random algorithm server host:" + randomAlgorithmServer.getHost() + ";port:" + randomAlgorithmServer.getPort());

4. Application client network request
The request code is generally the same as that in the Eureka application client running example.
5. cancel registration when application client is disabled
The cancellation code is generally the same as the running example of the Eureka application Client client.
6. Run the demo.
Create a new project (do not run in the same project as the demo of Application Service). Now let's sort out the complete Eureka application client and ribbon client integrated code.
/* * 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.InetSocketAddress;import java.net.Socket;import java.util.Date;import java.util.Iterator;import java.util.List;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import com.netflix.appinfo.ApplicationInfoManager;import com.netflix.appinfo.InstanceInfo.InstanceStatus;import com.netflix.appinfo.MyDataCenterInstanceConfig;import com.netflix.client.ClientFactory;import com.netflix.discovery.DefaultEurekaClientConfig;import com.netflix.discovery.DiscoveryManager;import com.netflix.loadbalancer.DynamicServerListLoadBalancer;import com.netflix.loadbalancer.RandomRule;import com.netflix.loadbalancer.Server;/** * Sample Eureka client that discovers the service using Eureka and sends * requests. * * @author Karthik Ranganathan * */public class SampleEurekaRibbonClient {private static final Logger logger = LoggerFactory.getLogger(SampleEurekaRibbonClient.class);public void sendRequestToServiceUsingEureka() {// Register with EurekaDiscoveryManager.getInstance().initComponent(new MyDataCenterInstanceConfig(),new DefaultEurekaClientConfig());ApplicationInfoManager.getInstance().setInstanceStatus(InstanceStatus.UP);// get LoadBalancer instance from configuration, properties fileDynamicServerListLoadBalancer lb = (DynamicServerListLoadBalancer) ClientFactory.getNamedLoadBalancer("myclient");// show all servers in the listList<Server> list = lb.getServerList(false);Iterator<Server> it = list.iterator();while (it.hasNext()) {Server server = it.next();logger.debug("application service host:" + server.getHost() + ";port=" + server.getPort());}// use RandomRule ‘s RandomRule algorithm to get a random server from lb ‘s server listRandomRule randomRule = new RandomRule();Server randomAlgorithmServer = randomRule.choose(lb, null);logger.debug("random algorithm server host:" + randomAlgorithmServer.getHost() + ";port:" + randomAlgorithmServer.getPort());// communicate with the serverSocket s = new Socket();try {s.connect(new InetSocketAddress(randomAlgorithmServer.getHost(), randomAlgorithmServer.getPort()));} catch (IOException e) {logger.error("Could not connect to the server :"+ randomAlgorithmServer.getHost() + " at port " + randomAlgorithmServer.getPort());}try {logger.debug("Connected to server. Sending a sample request");PrintStream out = new PrintStream(s.getOutputStream());out.println("Sample request " + new Date());String str = null;logger.debug("Waiting for server response..");BufferedReader rd = new BufferedReader(new InputStreamReader(s.getInputStream()));str = rd.readLine();if (str != null) {logger.debug("Received response from server. Communication all fine using Eureka :");logger.debug("Exiting the client. Demo over..");}rd.close();} catch (IOException e) {e.printStackTrace();logger.error(e.getMessage(), e);}this.unRegisterWithEureka();}public void unRegisterWithEureka() {// Un register from eureka.DiscoveryManager.getInstance().shutdownComponent();}public static void main(String[] args) {SampleEurekaRibbonClient sampleEurekaRibbonClient = new SampleEurekaRibbonClient();sampleEurekaRibbonClient.sendRequestToServiceUsingEureka();}}

Then, sort out the configuration file and log4j file and run sampleeurekaribbonclient. The log shows that the demo is successful.
References
  • Https://github.com/Netflix/ribbon/wiki/Programmers-Guide

Ribbon and Eureka Integration

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.