Ribbon负载均衡及Feign消费者调用服务

zllbirdonland 2019-12-08

微服务调用Ribbon

简介

前面讲了eureka服务注册与发现,但是结合eureka集群的服务调用没讲。

这里的话 就要用到Ribbon,结合eureka,来实现服务的调用;

Ribbon是Netflix发布的负载均衡器,它有助于控制HTTP和TCP的客户端的行为。为Ribbon配置服务提供者地址后,Ribbon就可基于某种负载均衡算法,自动地帮助服务消费者去请求。Ribbon默认为我们提供了很多负载均衡算法,例如轮询、随机等。当然,我们也可为Ribbon实现自定义的负载均衡算法。

Spring Cloud中,当Ribbon与Eureka配合使用时,Ribbon可自动从Eureka Server获取服务提供者地址列表,并基于负载均衡算法,请求其中一个服务提供者实例。展示了Ribbon与Eureka配合使用时的架构。

Ribbon负载均衡及Feign消费者调用服务

初步应用

Ribbon是客户端负载均衡,所以肯定集成再消费端,也就是consumer端

我们修改microservice-student-consumer-80

首先,引入依赖,pom.xml 加入 ribbon相关依赖

<!--ribbon相关依赖-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

application.yml

server:
  port: 8080
  context-path: /
eureka:
  client:
    service-url:
      defaultZone: http://eureka2001.huang.com:2001/eureka/,http://eureka2002.huang.com:2002/eureka/,http://eureka2003.huang.com:2003/eureka/
    register-with-eureka: false

ribbon结合eureka来调用服务提供者;

SpringCloudConfig也改成 要加个负载均衡配置 @LoadBalanced

package com.huang.microservicestudentconsumer80.config;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class SpringCloudConfig {

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

因为和eureka整合,所以启动类StudentConsumerApplication_80 加个注解 @EnableEurekaClient

这里还有一个,要修改下StudentConsumerController的PRE_HOST,改成指定的微服务应用名称;

当然这里要先在服务提供者microservice-student-provider-1001的application.yml加下配置,指定下应用名称:

application:

    name: microservice-student

Ribbon负载均衡及Feign消费者调用服务

我们的微服务应用名称是 microservice-student

所以服务调用者这边的控制器里PRE_HOST改成 http://MICROSERVICE-STUDENT即可;

MICROSERVICE-STUDENT为Eureka注册中心的应用名称

@RestController
@RequestMapping("/student")
public class StudentConsumerController {

    //    private final static String SERVER_IP_PORT = "http://localhost:1001";
    private final static String SERVER_IP_PORT = "http://MICROSERVICE-STUDENT";

上面配置好后,我们可以测试下;

先启动三个eureka,然后再启动服务提供者,再启动服务消费者;

Ribbon负载均衡及Feign消费者调用服务

Ribbon负载均衡及Feign消费者调用服务

结果就出来了,说明配置OK;

Ribbon负载均衡

按照它microservice-student-provider-1001建立一个microservice-student-provider子项目,然后将microservice-student-provider-1001这个子项目干掉;

前面搭建了初步例子,但是还没实现真正负载均衡,我们这里要先搞三个服务提供者集群,然后才能演示负载均衡,以及负载均衡策略;

新建项目microservice-student-provider-1002,microservice-student-provider-1003

pom.xml,application.yml,以及java类都复制一份,启动类名称对应的改下;

yml配置文件有两处要对应的改下,port端口改下,以及服务实例名称改下;

 Ribbon负载均衡及Feign消费者调用服务

相关代码如下

相关pom

<properties>
    <java.version>1.8</java.version>
</properties>
<dependencies>
    <dependency>
        <groupId>com.huang</groupId>
        <artifactId>microservice-common</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
    </dependency>
    <!--  修改后立即生效,热部署  -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>springloaded</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>
    <dependency>
        <groupId>com.huang</groupId>
        <artifactId>microservice-common</artifactId>
        <version>1.0-SNAPSHOT</version>
        <scope>compile</scope>
    </dependency>

    <!--添加注册中心Eureka相关配置-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-config</artifactId>
    </dependency>

    <!-- actuator监控引入 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
</dependencies>

Yml文件

---
server:
  port: 1001
  context-path: /
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/huang?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
  application:
    name: microservice-student
  profiles: provider-1001

eureka:
  instance:
    hostname: localhost
    appname: microservice-student
    instance-id: microservice-student:1001
    prefer-ip-address: true
  client:
    service-url:
      defaultZone: http://eureka2001.huang.com:2001/eureka/,http://eureka2002.huang.com:2002/eureka/,http://eureka2003.huang.com:2003/eureka/

info:
  groupId: com.huang.testSpringcloud
  artifactId: microservice-student-provider-1001
  version: 1.0-SNAPSHOT
  userName: http://huang.com
  phone: 123456

---
server:
  port: 1002
  context-path: /
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/huang?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
  application:
    name: microservice-student
  profiles: provider-1002

eureka:
  instance:
    hostname: localhost
    appname: microservice-student
    instance-id: microservice-student:1002
    prefer-ip-address: true
  client:
    service-url:
      defaultZone: http://eureka2001.huang.com:2001/eureka/,http://eureka2002.huang.com:2002/eureka/,http://eureka2003.huang.com:2003/eureka/

info:
  groupId: com.huang.testSpringcloud
  artifactId: microservice-student-provider-1002
  version: 1.0-SNAPSHOT
  userName: http://huang.com
  phone: 123456

---
server:
  port: 1003
  context-path: /
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/huang?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
  application:
    name: microservice-student
  profiles: provider-1003

eureka:
  instance:
    hostname: localhost
    appname: microservice-student
    instance-id: microservice-student:1003
    prefer-ip-address: true
  client:
    service-url:
      defaultZone: http://eureka2001.huang.com:2001/eureka/,http://eureka2002.huang.com:2002/eureka/,http://eureka2003.huang.com:2003/eureka/

info:
  groupId: com.huang.testSpringcloud
  artifactId: microservice-student-provider-1003
  version: 1.0-SNAPSHOT
  userName: http://huang.com
  phone: 123456

启动类

package com.huang.microservicestudentprovider;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@EntityScan("com.huang.*.*")
@EnableEurekaClient
@SpringBootApplication
public class MicroserviceStudentProviderApplication {

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

}

StudentProviderController.java

@Value("${server.port}")
private String port;

@RequestMapping("/ribbon")
public String ribbon(){
    return "工号【"+port+"】正在为您服务";
}

StudentConsumerController.java

@RequestMapping("/ribbon")
public String ribbon(){
    return restTemplate.getForObject(SERVER_IP_PORT + "/student/ribbon", String.class);
}

先测试服务提供者:

http://localhost:1001/student/list

http://localhost:1002/student/list

http://localhost:1003/student/list

看看是否有结果;

再测试下 eureka:

http://eureka2001.javaxl.com:2001/

http://eureka2002.javaxl.com:2002/

http://eureka2003.javaxl.com:2003/

Ribbon负载均衡及Feign消费者调用服务

有这种的话,就说明没问题;

然后再启动服务消费者:

http://localhost/student/list  多刷新几次 看控制台,我们看到 有默认的轮询策略,访问对应的服务提供者;

但是这种默认的轮询策略肯定是不能满足实际需求的,比如有3个服务提供者,突然挂了一个,这样的话,默认轮询 ,总有1/3的概率访问失败; 所以我们看下ribbon默认给我们提供的策略有哪些;

策略名

策略声明

策略描述

BestAvailableRule

public class BestAvailableRule extends ClientConfigEnabledRoundRobinRule

选择一个最小的并发请求的server

AvailabilityFilteringRule

public class AvailabilityFilteringRule extends PredicateBasedRule

过滤掉那些因为一直连接失败的被标记为circuit tripped的后端server,并过滤掉那些高并发的的后端server(active connections 超过配置的阈值)

WeightedResponseTimeRule

public class WeightedResponseTimeRule extends RoundRobinRule

根据响应时间分配一个weight,响应时间越长,weight越小,被选中的可能性越低。

RetryRule

public class RetryRule extends AbstractLoadBalancerRule

对选定的负载均衡策略机上重试机制。

RoundRobinRule

public class RoundRobinRule extends AbstractLoadBalancerRule

roundRobin方式轮询选择server

RandomRule

public class RandomRule extends AbstractLoadBalancerRule

随机选择一个server

ZoneAvoidanceRule

public class ZoneAvoidanceRule extends PredicateBasedRule

复合判断server所在区域的性能和server的可用性选择server

默认7个策略,根据具体产品需求,我们选用;

代码中如何假如呢;

服务消费端 SpringCloudConfig配置类  

指定IRule实现;

这里我们演示用 RetryRule,大伙可以自行测试;

package com.huang.microservicestudentconsumer80.config;

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RetryRule;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class SpringCloudConfig {

    @LoadBalanced  // 引入ribbon负载均衡
    @Bean
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }

    /**
     * 自定义轮询算法
     * @return
     */
    @Bean
    public IRule myRule(){
        return new RetryRule();
    }
}

相关推荐