Spring cloud ribbon load balancing instance analysis

This article mainly introduces the spring cloud ribbon load balancing example analysis, which is introduced in great detail through the example code, which has certain reference value for everyone's study or work. Friends in need can refer to it

Spring cloud integrates ribbon and Eureka to realize load balancing on the client.

An example is implemented below, and the structure is shown in the figure below.

1、 Server side

1. Create project

Development tool: IntelliJ idea 2019.2 three

Create a new springboot project named "cloud server" in the idea, and select 2.1 as the springboot version 10. Check spring cloud discover - > in the interface of selecting dependencies

Eureka server, POM after creation The latest stable version of springcloud is automatically added to the XML configuration file, which is currently Greenwich. XML SR3。

pom. The complete contents of the XML are as follows:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.10.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <groupId>com.example</groupId>
  <artifactId>cloud-server</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>cloud-server</name>
  <description>Demo project for Spring Boot</description>

  <properties>
    <java.version>1.8</java.version>
    <spring-cloud.version>Greenwich.SR3</spring-cloud.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>${spring-cloud.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

</project>

2. Modify the configuration application yml

server:
 port: 8761
eureka:
 client:
  register-with-eureka: false
  fetch-registry: false

3. Modify the startup class code cloudserverapplication java

Add annotation @ enableeurekaserver

package com.example.cloudserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class CloudServerApplication {

  public static void main(String[] args) {
    SpringApplication.run(CloudServerApplication.class,args);
  }

}

2、 Service provider

1. Create project

Create a new springboot project in the idea. Except for the name "cloud provider", other steps are the same as creating the server side above.

2. Modify the configuration application yml

spring:
 application:
  name: cloud-provider
eureka:
 instance:
  hostname: localhost
 client:
  serviceUrl:
   defaultZone: http://localhost:8761/eureka/

3. Modify the startup class code cloudproviderapplication java

Add annotation @ enableeurekaclient;

Let the class read the console input at startup and decide which port to use to start the server;

Add a controller method for testing.

package com.example.cloudprovider;

//import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Scanner;

@SpringBootApplication
@EnableEurekaClient
@RestController
public class CloudProviderApplication {

  public static void main(String[] args) {
    //SpringApplication.run(CloudProviderApplication.class,args);
    Scanner scan = new Scanner(system.in);
    String port = scan.nextLine();
    new SpringApplicationBuilder(CloudProviderApplication.class).properties("server.port=" + port).run(args);
  }

  @RequestMapping("/")
  public String index(HttpServletRequest request) {
    return request.getRequestURL().toString();
  }
}

3、 Service caller

1. Create project

Create a new springboot project in the idea. Except for the name "cloud invoker", other steps are the same as creating the server side above.

2. Modify the configuration application yml

server:
 port: 9000
spring:
 application:
  name: cloud-invoker
eureka:
 instance:
  hostname: localhost
 client:
  serviceUrl:
   defaultZone: http://localhost:8761/eureka/

3. Modify the startup class code cloudinvokerapplication java

Add annotation @ enablediscoveryclient.

package com.example.cloudinvoker;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class CloudInvokerApplication {

  public static void main(String[] args) {
    SpringApplication.run(CloudInvokerApplication.class,args);
  }

}

4. There are two ways to configure the ribbon: using code and using configuration file

Method 1: use code

(1) Create a custom load rule class myrule.java

Ribbon's load balancer interface defines the operation of the server, which is mainly used for server selection.

All servers can be returned by calling the getallservers method of iloadbalancer. Here, only the first server is returned.

package com.example.cloudinvoker;

import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.Server;

import java.util.List;

public class MyRule implements IRule {

  private ILoadBalancer iLoadBalancer;

  @Override
  public Server choose(Object o) {
    List<Server> servers = iLoadBalancer.getAllServers();
    System.out.println("自定义服务器规则类,输出服务器信息:");
    for(Server s: servers){
      System.out.println(" " + s.getHostPort());
    }
    return servers.get(0);
  }

  @Override
  public void setLoadBalancer(ILoadBalancer iLoadBalancer) {
    this.iLoadBalancer = iLoadBalancer;
  }

  @Override
  public ILoadBalancer getLoadBalancer() {
    return this.iLoadBalancer;
  }
}

(2) Create a new Ping class myping.java

The load balancer provides a ping mechanism to Ping the server every other period of time to judge whether the server is alive.

The implementation class of iping interface is responsible for this work.

package com.example.cloudinvoker;

import com.netflix.loadbalancer.IPing;
import com.netflix.loadbalancer.Server;

public class MyPing implements IPing {

  @Override
  public boolean isAlive(Server server) {
    System.out.println("自定义Ping类,服务器信息:" + server.getHostPort() + ",状态:" + server.isAlive());
    return true;
  }
}

(3) Create a new configuration class myconfig.java

package com.example.cloudinvoker.config;

import com.example.cloudinvoker.MyPing;
import com.example.cloudinvoker.MyRule;
import com.netflix.loadbalancer.IPing;
import com.netflix.loadbalancer.IRule;
import org.springframework.context.annotation.Bean;

public class MyConfig {
  @Bean
  public IRule getRule(){
    return new MyRule();
  }
  @Bean
  public IPing getPing(){
    return new MyPing();
  }
}

(4) Create a new configuration class cloudproviderconfig.java

package com.example.cloudinvoker.config;

import org.springframework.cloud.netflix.ribbon.RibbonClient;

@RibbonClient(name = "cloud-provider",configuration = MyConfig.class)
public class CloudProviderConfig {
}

Method 2: use configuration file

Comment out the two configuration classes of mode 1 in application Add the following configuration to the last side of YML

cloud-provider:
 ribbon:
  NFLoadBalancerRuleClassName: com.example.cloudinvoker.MyRule
  NFLoadBalancerPingClassName: com.example.cloudinvoker.MyPing
  listOfServers: http://localhost:8080/,http://localhost:8081/

5. Add controller invokercontroller java

package com.example.cloudinvoker;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@Configuration
public class InvokerController {

  @LoadBalanced
  @Bean
  public RestTemplate getRestTemplate(){
    return new RestTemplate();
  }

  @RequestMapping(value="/router",method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
  public String router(){
    RestTemplate restTemplate = getRestTemplate();
    //根据名称调用服务
    String json = restTemplate.getForObject("http://cloud-provider/",String.class);
    return json;
  }
}

4、 Testing

1. Start the server side.

2. Start the two service providers by entering 8080 and 8081 respectively in the console.

3. Start the service caller.

4. Browser access http://localhost:9000/router , refresh the page several times, and the results are:

http://localhost:8081/

Service caller project idea console timing output:

自定义服务器规则类,输出服务器信息:
 localhost:8081
 localhost:8080
自定义Ping类,服务器信息:localhost:8081,状态:true
自定义Ping类,服务器信息:localhost:8080,状态:true

The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>