分布式springcloud,Ribbon负载均衡、Feign的使用

分布式springcloud,Ribbon负载均衡、Feign的使用

Ribbon

Ribbon简介

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

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

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

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

在这里插入图片描述

调用Ribbon

初步应用

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加

eureka:
  client:
    register-with-eureka: false #false 由于注册中心的职责就是维护服务实例,它并不需要去检索服务,所以也设置为false
    service-url:
      defaultZone: http://eureka2001.hu.com:2001/eureka/,http://eureka2002.hu.com:2002/eureka/,http://eureka2003.hu.com:2003/eureka/

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

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

/**
     * 调用服务模版
     * @return
     */
    @Bean
    @LoadBalanced  // 引入ribbon负载均衡
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

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

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

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

application:
    name: microservice-student

在这里插入图片描述

我们的微服务应用名称是 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,然后再启动服务提供者,再启动服务消费者;
在这里插入图片描述
执行 http://localhost/student/list
在这里插入图片描述
结果就出来了,说明配置OK;

Ribbon负载均衡

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

新建项目microservice-student-provider,里面的内容都是差不多的。yml文件有不同,模拟三个服务提供者。方法跟上一次讲的一样的。
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.hu</groupId>
        <artifactId>t224springcloud</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>microservice-student-provider</artifactId>


    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.hu</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>org.springframework.boot</groupId>
            <artifactId>microservice-common</artifactId>
            <version>2.2.1.RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.hu</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>

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

</project>

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/tb_stu?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.hu.com:2001/eureka/,http://eureka2002.hu.com:2002/eureka/,http://eureka2003.hu.com:2003/eureka/

info:
  groupId: com.hu.t224Springcloud
  artifactId: microservice-student-provider-1001
  version: 1.0-SNAPSHOT
  userName: http://java.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/tb_stu?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.hu.com:2001/eureka/,http://eureka2002.hu.com:2002/eureka/,http://eureka2003.hu.com:2003/eureka/

info:
  groupId: com.hu.t224Springcloud
  artifactId: microservice-student-provider-1002
  version: 1.0-SNAPSHOT
  userName: http://java.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/tb_stu?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.hu.com:2001/eureka/,http://eureka2002.hu.com:2002/eureka/,http://eureka2003.hu.com:2003/eureka/

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

如何查看我是使用哪一个服务呢?不急。还有小小的测试代码

启动类

package com.hu.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.hu.*.*")
@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/student/list 多刷新几次 看控制台,我们看到 有默认的轮询策略,访问对应的服务提供者;

在这里插入图片描述

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

策略类 命名 说明
RandomRule 随机策略 随机选择 Server
RoundRobinRule 轮训策略 按顺序循环选择 Server
RetryRule 重试策略 在一个配置时问段内当选择 Server 不成功,则一直尝试选择一个可用的 Server
BestAvailableRule 最低并发策略 逐个考察 Server,如果 Server 断路器打开,则忽略,再选择其中并发连接最低的 Server
AvailabilityFilteringRule 可用过滤策略 过滤掉一直连接失败并被标记为 circuit tripped 的 Server,过滤掉那些高并发连接的 Server(active connections 超过配置的网值)
ResponseTimeWeightedRule 响应时间加权策略 根据 Server 的响应时间分配权重。响应时间越长,权重越低,被选择到的概率就越低;响应时间越短,权重越高,被选择到的概率就越高。这个策略很贴切,综合了各种因素,如:网络、磁盘、IO等,这些因素直接影响着响应时间
ZoneAvoidanceRule 区域权衡策略 综合判断 Server 所在区域的性能和 Server 的可用性轮询选择 Server,并且判定一个 AWS Zone 的运行性能是否可用,剔除不可用的 Zone 中的所有 Server

默认7个策略,根据具体产品需求,我们选用;
代码中如何假如呢;
服务消费端 SpringCloudConfig配置类
指定IRule实现;
这里我们演示用 RetryRule

package com.hu.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;

/**
 * @author hu
 * @site www.huguiyun.xzy
 * @company xxx公司
 * @create  2019-11-18 18:08
 */

@Configuration
public class SpringCloudConfig {

    @LoadBalanced  // 引入ribbon负载均衡
    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
    /**
     * 自定义轮询算法
     * @return
     */
    @Bean
    public IRule myRule(){
       return new RetryRule();
    }
}

Feign

简介

声明式服务调用Feign简单介绍下;

Feign是一个声明式的Web Service客户端,它使得编写Web Serivce客户端变得更加简单。我们只需要使用Feign来创建一个接口并用注解来配置它既可完成。它具备可插拔的注解支持,包括Feign注解和JAX-RS注解。Feign也支持可插拔的编码器和解码器。Spring Cloud为Feign增加了对Spring MVC注解的支持,还整合了Ribbon和Eureka来提供均衡负载的HTTP客户端实现。

这段话看起来比较懵逼,这里说下实际使用,前面Ribbon调用服务提供者,我们通过restTemplate调用,缺点是,多个地方调用,同一个请求要写多次,不方便统一维护,这时候Feign来了,就直接把请求统一搞一个service作为FeignClient,然后其他调用Controller需要用到的,直接注入service,直接调用service方法即可;同时Feign整合了Ribbon和Eureka,所以要配置负载均衡的话,直接配置Ribbon即可,无其他特殊地方;当然Fiegn也整合了服务容错保护,断路器Hystrix,后面再说。

应用

1、在common项目里建一个service(实际项目肯定是多个service)作为Feign客户端,用Feign客户端来调用服务器提供者,当然可以配置负载均衡;Feign客户端定义的目的,就是为了方便给其他项目调用;
修改 microservice-common-------公共项目
pom.xml引入Feign依赖:

<?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>com.hu</groupId>
        <artifactId>t224springcloud</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>microservice-common</artifactId>


    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <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>

        <!--引入Feign依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>

    </dependencies>

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

</project>

我们定义了 FeignClient,同时指定了调用的服务名称MICROSERVICE-STUDENT
common项目修改后,maven clean下 然后install下;

建StudentClientService接口;因为在消费方里面一般有大量的controller层,而controller层里面有很多的相同的代码,我们就把这个相同的代码向上抽取到公共项目里面来,减少代码量。而且我们的端口改变的话修改起来有会很麻烦!向上抽取这样就方便很多。如果要修改的话直接在公共项目里面修改就行。。

package com.hu.microservicecommon.service;

import com.hu.microservicecommon.entity.Student;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@FeignClient(value="MICROSERVICE-STUDENT")
public interface StudentClientService {
 
    /**
     * 根据id查询学生信息
     * @param id
     * @return
     */
    @GetMapping(value="/student/get/{id}")
    public Student get(@PathVariable("id") Integer id);
     
    /**
     * 查询学生信息
     * @return
     */
    @GetMapping(value="/student/list")
    public List<Student> list();
     
    /**
     * 添加或者修改学生信息
     * @param student
     * @return
     */
    @PostMapping(value="/student/save")
    public boolean save(Student student);
     
    /**
     * 根据id删除学生信息
     * @return
     */
    @GetMapping(value="/student/delete/{id}")
    public boolean delete(@PathVariable("id") Integer id);

    @RequestMapping("/student/ribbon")
    public String ribbon();
}

2、新建一个Feign消费者项目;
参考microservice-student-consumer-80建一个microservice-student-consumer-feign-80
代码都复制一份,包括pom.xml
在这里插入图片描述

pom.xml加上feign的依赖,

 <!--引入Feign依赖-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-feign</artifactId>
    </dependency>

SpringCloudConfig.java

package com.hu.microservicestudentconsumerfeign80.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;

/**
 * @author hu
 * @site www.huguiyun.xzy
 * @company xxx公司
 * @create  2019-11-18 18:08
 */

@Configuration
public class SpringCloudConfig {

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


    /**
     * 自定义重试策略
     * @return
     */
    @Bean
    public IRule myRule(){
        return new RetryRule();
    }
}

修改启动类名称,和加注解
启动类名称改下,改成StudentConsumerFeignApplication_80,同时加个注解@EnableFeignClients
支持下Feign;

package com.hu.microservicestudentconsumerfeign80;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;


@EnableEurekaClient
@EnableFeignClients(value = "com.hu.*.*")
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class MicroserviceStudentConsumerFeign80Application {

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

这里就可以解决前面一个尴尬的问题就是我其中的一个服务断了,就会报错。重试策略。
负载均衡这样就成功了哟!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章