Spring Cloud Ribbon客户端负载均衡

Spring Cloud Ribbon客户端负载均衡

目录

  1. Ribbon简介
  2. RestTemplate详解
  3. Spring Cloud Ribbon配置

为了提高服务的可用性,我们一般会将相同的服务部署多个实例,负载均衡的作用就是使获取服务的请求被均衡的分配到各个实例中。负载均衡一般分为服务端负载均衡和客户端负载均衡,服务端的负载均衡通过硬件(如F5)或者软件(如Nginx)来实现,而Ribbon实现的是客户端负载均衡。服务端负载均衡是在硬件设备或者软件模块中维护一份可用服务清单,然后客户端发送服务请求到这些负载均衡的设备上,这些设备根据一些算法均衡的将请求转发出去。而客户端负载均衡则是客户端自己从服务注册中心(如之前提到的Eureka Server)中获取服务清单缓存到本地,然后通过Ribbon内部算法均衡的去访问这些服务。

Ribbon简介

Ribbon是由Netflix开发的一款基于HTTP和TCP的负载均衡的开源软件。我们可以直接给Ribbon配置好服务列表清单,也可以配合Eureka主动的去获取服务清单,需要使用到这些服务的时候Ribbon通过轮询或者随机等均衡算法去获取服务。
在Spring Cloud Eureka服务治理一节中,我们已经在Server-Consumer中配置了Ribbon,并通过加了@LoadBalanced注解的RestTemplate对象去均衡的消费服务,所以这节主要记录的是RestTemplate的详细使用方法和一些额外的Ribbon配置。

RestTemplate详解

从名称上来看就可以知道它是一个用来发送REST请求的摸板,所以包含了GET,POST,PUT,DELETE等HTTP Method对应的方法。

在之前的项目Spring Cloud Eureka服务治理上继续添加代码
只需要用到Eureka-Server和Eureka-Client

Eureka-Server不变Eureka-Client基础上加以下代码:
在这里插入图片描述

UserController类:

@RestController
@RequestMapping("user")
public class UserController {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @GetMapping("/{id:\\d+}")
    public User get(@PathVariable Long id) {
        log.info("获取用户id为 " + id + "的信息");
        return new User(id, "mrbird", "123456");
    }

    @GetMapping
    public List<User> get() {
        List<User> list = new ArrayList<>();
        list.add(new User(1L, "mrbird", "123456"));
        list.add(new User(2L, "scott", "123456"));
        log.info("获取用户信息 " + list);
        return list;
    }

    @PostMapping
    public void add(@RequestBody User user) {
        log.info("新增用户成功 " + user);
    }

    @PutMapping
    public void update(@RequestBody User user) {
        log.info("更新用户成功 " + user);
    }

    @DeleteMapping("/{id:\\d+}")
    public void delete(@PathVariable Long id) {
        log.info("删除用户成功 " + id);
    }

}

User类:

public class User implements Serializable {

    private static final long serialVersionUID = 1339434510787399891L;
    private Long id;

    private String username;

    private String password;

    public User() {
    }

    public User(Long id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

创建一个SpringBoot项目,名字:ribbon-consumer项目结构:
在这里插入图片描述

pom.xml

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zlx</groupId>
    <artifactId>Ribbon-Consumer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>Ribbon-Consumer</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.13.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Edgware.SR3</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-ribbon</artifactId>
        </dependency>
    </dependencies>

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

</project>

然后编写启动类

@EnableDiscoveryClient
@SpringBootApplication
public class RibbonConsumerApplication {
    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
    public static void main(String[] args) {
        SpringApplication.run(RibbonConsumerApplication.class, args);
    }

}

application.yml

server:
  port: 9000

spring:
  application:
    name: Server-Consumer

eureka:
  client:
    serviceUrl:
      defaultZone: http://root:root@peer1:80/eureka/,http://root:root@peer2:81/eureka/

User类:

public class User implements Serializable {

    private static final long serialVersionUID = 1339434510787399891L;
    private Long id;
    private String username;
    private String password;

    public User() {
    }

    public User(Long id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

TestController类:

@RestController
public class TestController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("user/{id:\\d+}")
    public User getUser(@PathVariable Long id) {
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        URI uri = UriComponentsBuilder.fromUriString("http://Server-Provider/user/{id}")
                .build().expand(params).encode().toUri();
        return this.restTemplate.getForEntity(uri, User.class).getBody();
    }

    @GetMapping("user")
    public List<User> getUsers() {
        return this.restTemplate.getForObject("http://Server-Provider/user", List.class);
    }

    @GetMapping("user/add")
    public String addUser() {
        User user = new User(1L, "mrbird", "123456");
        HttpStatus status = this.restTemplate.postForEntity("http://Server-Provider/user", user, null).getStatusCode();
        if (status.is2xxSuccessful()) {
            return "新增用户成功";
        } else {
            return "新增用户失败";
        }
    }

    @GetMapping("user/update")
    public void updateUser() {
        User user = new User(1L, "mrbird", "123456");
        this.restTemplate.put("http://Server-Provider/user", user);
    }

    @GetMapping("user/delete/{id:\\d+}")
    public void deleteUser(@PathVariable Long id) {
        this.restTemplate.delete("http://Server-Provider/user/{1}", id);
    }
}


发送Get请求

RestTemplate中与GET请求对应的方法有getForEntity和getForObject。
getForEntity
getForEntity方法返回ResponseEntity对象,该对象包含了返回报文头,报文体和状态码等信息。getForEntity有三个重载方法:

  1. getForEntity(String url, Class responseType, Object…uriVariables);
  2. getForEntity(String url, Class responseType,Map<String, ?> uriVariables);
  3. getForEntity(URI url, Class responseType);

第一个参数为Url,第二个参数为返回值的类型,第三个参数为请求的参数(可以是数组,也可以是Map)。
在Testcontroller中举个getForEntity(String url, Class<.T> responseType, Object… uriVariables)的使用例子:

@GetMapping("user/{id:\\d+}")
public User getUser(@PathVariable Long id) {
    return this.restTemplate.getForEntity("http://Server-Provider/user/{name}", User.class, id).getBody();
}

{1}为参数的占位符,匹配参数数组的第一个元素。因为第二个参数指定了类型为User,所以调用getBody方法返回类型也为User。

方法参数除了可以放在数组里外,也可以放在Map里,举个getForEntity(String url, Class<T.> responseType, Map<String, ?> uriVariables)使用例子:

@GetMapping("user/{id:\\d+}")
public User getUser(@PathVariable Long id) {
    Map<String, Object> params = new HashMap<>();
    params.put("id", id);
    return this.restTemplate.getForEntity("http://Server-Provider/user/{id}", User.class, params).getBody();
}

只有两个参数的重载方法getForEntity(URI url, Class<.T> responseType)第一个参数接收java.net.URI类型,可以通过org.springframework.web.util.UriComponentsBuilder来创建,举个该方法的使用例子:

@GetMapping("user/{id:\\d+}")
public User getUser(@PathVariable Long id) {
    Map<String, Object> params = new HashMap<>();
    params.put("id", id);
    URI uri = UriComponentsBuilder.fromUriString("http://Server-Provider/user/{id}")
            .build().expand(params).encode().toUri();
    return this.restTemplate.getForEntity(uri, User.class).getBody();
}

其中expand方法也可以接收数组和Map两种类型的参数。

getForObject

getForObject方法和getForEntity方法类似,getForObject方法相当于getForEntity方法调用了getBody方法,直接返回结果对象,为不是ResponseEntity对象。
getForObject方法和getForEntity方法一样,也有三个重载方法,参数类型和getForEntity方法一致,所以不再列出。

发送POST请求

使用RestTemplate发送PUT请求,使用的是它的put方法,put方法返回值是void类型,该方法也有三个重载方法:

  1. put(String url, Object request, Object… uriVariables);
  2. put(String url, Object request, Map<String, ?> uriVariables);
  3. put(URI url, Object request)。
@GetMapping("user/update")
public void updateUser() throws JsonProcessingException {
    User user = new User(1L, "mrbird", "123456");
    this.restTemplate.put("http://Server-Provider/user", user);
}

在RESTful风格的接口中,判断成功失败不再是通过返回值的某个标识来判断的,而是通过返回报文的状态码是否为200来判断。当这个方法成功执行并返回时,返回报文状态为200,即可判断方法执行成功。

发送DELETE请求

使用RestTemplate发送DELETE请求,使用的是它的delete方法,delete方法返回值是void类型,该方法也有三个重载方法:

  1. delete(String url, Object… uriVariables);
  2. delete(String url, Map<String, ?> uriVariables);
  3. delete(URI url)。
@GetMapping("user/delete/{id:\\d+}")
public void deleteUser(@PathVariable Long id) {
    this.restTemplate.delete("http://Server-Provider/user/{1}", id);
}

我们分别启动两个Eureka Server用于集群,Eureka Client实例,然后启动Ribbon-Consumer。
访问http://localhost:9000/user/1(后面每个方法我们都访问两次,用于观察负载均衡),返回结果如下:
在这里插入图片描述

Spring Cloud Ribbon配置

Spring Cloud Ribbon的配置分为全局和指定服务名称。比如我要指定全局的服务请求连接超时时间为200毫秒:

ribbon:
  ConnectTimeout: 200

如果只是设置获取Server Provider服务的请求连接超时时间,我们只需要在配置最前面加上服务名称就行了,如:

Server-Provider:
  ribbon:
    ConnectTimeout: 200

设置获取Server-Provider服务的负载均衡算法从轮询改为随机:

Server-Provider:
  ribbon:
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

设置处理Server-Provider服务的超时时间:

Server-Provider:
  ribbon:
    ReadTimeout: 1000

开启重试机制,即获取服务失败是否从另外一个节点重试,默认值为false:

spring:
  cloud:
    loadbalancer:
      retry:
        enabled: true

对Server-Provider的所有请求在失败的时候都进行重试:

Server-Provider:
  ribbon:
    OkToRetryOnAllOperations: true

切换Server-Provider实例的重试次数:

Server-Provider:
  ribbon:
    MaxAutoRetriesNextServer: 1

对Server-Provider当前实例的重试次数:

Server-Provider:
  ribbon:
    MaxAutoRetries: 1

根据如上配置当访问Server-Provider服务实例(比如是82)遇到故障的时候,Ribbon会再尝试访问一次当前实例(次数由MaxAutoRetries配置),如果不行,就换到83实例进行访问(更换次数由 MaxAutoRetriesNextServer决定),如果还是不行,那就GG思密达,返回失败。
如果不和Eureka搭配使用的话,我们就需要手动指定服务清单给Ribbon:

Server-Provider:
  ribbon:
    listOfServers: localhost:82,localhost:83

猜你喜欢

转载自blog.csdn.net/weixin_43538859/article/details/86615437