Netflix's first Ribbon program (6)

Introduction to Ribbon

Ribbon is a well-established client-side IPC library for cloud services that provides some of the following features:

  1. load balancing
  2. fault tolerance
  3. Supports multi-protocol communication (HTTP, TCP, UDP) in an asynchronous and dynamic model
  4. Cache and batch processing

To introduce Ribbon dependencies, you can go to Ribbon's maven repository to get them. The following is an example of maven introduction:

<dependency>
    <groupId>com.netflix.ribbon</groupId>
    <artifactId>ribbon</artifactId>
    <version>2.2.2</version>
</dependency>

Modules included in Ribbon

  1. ribbon: APIs for integrating load balancing, fault tolerance, caching/batching on other Ribbon modules and Hystrix
  2. ribbon-loadbalancer: API for load balancer that can be used independently or with other modules
  3. ribbon-eureka: API to provide dynamic server list to cloud using Eureka client
  4. ribbon-transport: A transport client supporting HTTP, TCP and UDP protocols using RxNetty with load balancing
  5. ribbon-httpclient: Built on top of Apache HttpClient, a REST client integrated with a load balancer
  6. ribbon-example: provides some examples
  7. ribbon-core: client-side configuration api and other shared apis

We will use a few modules marked in blue font for demonstration purposes.

Load Balancer Components

Basic functions provided by Ribbon

  1. Provide communication clients with a public DNS name or the IP of a single server
  2. Select servers based on specific logic

Advanced features provided by Ribbon

  1. Create an association between clients and servers by dividing clients into zones (such as racks in a data center), reducing server latency in the same zone
  2. Maintain server statistics to avoid servers with high latency or frequent failures
  3. Maintain zone statistics to avoid areas where downtime is likely

Three sub-modules of load balancer

  1. Rule: The logical component that determines which service is returned from the list
  2. Ping: A component that runs in the background to keep the service alive
  3. ServerList: This can be static or dynamic. If it's dynamic (used by DynamicServerListLoadBalancer), a background thread will refresh and filter the list at specific intervals

Create Ribbon Program


As shown in the architecture diagram, Ribbon acts as a load balancer, which enables our service consumers to call the services they want to use. Service consumers do not need to care about the specific operations in the middle, but only need to tell the load balancer about the service information to be called. , Ribbon will select an available server from the corresponding service cluster for service consumers to call.

We create two simple maven projects, ribbon-server and ribbon-client, ribbon-server acts as a server, provides services, and starts two different service instances (with different ports), and ribbon-client acts as a client and initiates service calls. In order to facilitate the construction of the project, we use Spring Boot here (if you don't know Spring Boot, you can check the simple use of Spring Boot (2) for a general understanding) to quickly start, visit the Spring Boot official website to get the latest dependencies, The latest stable version I use here is 2.0.1, which is added to the pom.xml of our ribbon-server project:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.0.1.RELEASE</version>
</dependency>

Create a new com.init.springCloud package under ribbon-server, create a startup class ServerApp, and use the console to enter different ports to start different projects. The code is as follows:

package com.init.springCloud;

import java.util.Scanner;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;

@SpringBootApplication
public class ServerApp {

	public static void main(String[] args) {
		@SuppressWarnings("resource")
		Scanner scan = new Scanner(System.in);
		String port = scan.nextLine();
		new SpringApplicationBuilder(ServerApp.class).properties("server.port=" + port).run(args);
	}

}

Create another controller class ServerController to return the information of the current service. Here we let the service return the information of a Person class. The codes of the two classes are as follows:

package com.init.springCloud;

import lombok.Data;
//Lombok is used here, students who do not use this can remove the following annotation, and then manually add getter and setter methods
@Data
public class Person {

	private Integer id;			//主键ID
	private String name;		//姓名
	private String info; //Information, view the source of the service according to the URL address
	
}
package com.init.springCloud;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ServerController {

	@RequestMapping(value = "/search/{id}", method = RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public Person searchPerson(@PathVariable Integer id,HttpServletRequest request){
		Person person = new Person();
		person.setId(id);
		person.setName("Spirit");
		person.setInfo(request.getRequestURL().toString());
		return person;
	}
	
}

Run the main() method of the ServerApp class, enter 8082 to start the first server service; start the main() method again, enter 8083 to start the second server service.

Then introduce Ribbon's dependencies for the ribbon-client project, enter the Ribbon dependency warehouse , and introduce Ribbon's core package ribbon-core and http request package ribbon-httpclient. In terms of version, I'm introducing the latest stable version 2.2.5.

<dependency>
    <groupId>com.netflix.ribbon</groupId>
    <artifactId>ribbon-core</artifactId>
    <version>2.2.5</version>
</dependency>
<dependency>
    <groupId>com.netflix.ribbon</groupId>
    <artifactId>ribbon-httpclient</artifactId>
    <version>2.2.5</version>
</dependency>

Then also create the com.init.springCloud package under the ribbon-client project, create a new RibbonTest class, and refer to Ribbon's GitHub documentation to create a load request. The code is as follows:

package com.init.springCloud;

import com.netflix.client.ClientException;
import com.netflix.client.ClientFactory;
import com.netflix.client.http.HttpRequest;
import com.netflix.client.http.HttpResponse;
import com.netflix.config.ConfigurationManager;
import com.netflix.niws.client.http.RestClient;

public class RibbonTest {

	public static void main(String[] args) {
		
		//Set the server to request
		ConfigurationManager.getConfigInstance().setProperty(
	      		"sample-client.ribbon.listOfServers",
	      		"localhost:8082,localhost:8083");
		//Set up the REST request client
		RestClient client = (RestClient) ClientFactory.getNamedClient("sample-client");
		//create request instance
		HttpRequest request = HttpRequest.newBuilder().uri("/search/1").build();
		//Send 10 consecutive requests to the server
		for(int i=0; i<10; i++){
			try {
				HttpResponse response = client.executeWithLoadBalancer(request);
				String result = response.getEntity(String.class);
				System.out.println("Request result: "+result);
			} catch (ClientException e) {
				e.printStackTrace ();
			} catch (Exception e) {
				e.printStackTrace ();
			}
		}
		
	}
	
}

When I quoted the Ribbon Quick Start document provided by Netflix, there were some problems. Because the document is quite old, the example cannot be used directly, so I made some modifications. At the same time, ribbon-httpclient is based on Apache's Http request. Ribbon deprecated this method and switched to its own internal http method. Time relationship. I didn't find this alternative method when I checked the documentation, so I gave up. If you have a friend who has solved this problem, you can share it with I.

Running the main() method of the RibbonTest class, we can see that the test class method polls for two services:


The reason to request two services in turn is to call the RoundRobinRule in Ribbon's Rule rule, which is Ribbon's default request rule. More detailed information on Ribbon will be updated later.

Source code click here

Spring Cloud series:

Spring Cloud introduction and environment construction (1)

Simple use of Spring Boot (2)

Simple example of Spring Cloud service management framework Eureka (3)

Spring Cloud service management framework Eureka project cluster (4)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325592879&siteId=291194637