分佈式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);
    }
}

這裏就可以解決前面一個尷尬的問題就是我其中的一個服務斷了,就會報錯。重試策略。
負載均衡這樣就成功了喲!!!

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