1. 程式人生 > >SpringCloud Zuul實現負載均衡和熔斷機制

SpringCloud Zuul實現負載均衡和熔斷機制

一、場景

筆者就Zuul閘道器下實現其負載均衡與熔斷機制(雪崩)進行實踐,前提是已經匯入zuul相關依賴

springboot版本:1.5.9.RELEASE

springcloud版本:Dalston.SR5

<dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
        </dependency>
        <dependency>
            <groupId>com.netflix.zuul</groupId>
            <artifactId>zuul-core</artifactId>
            <version>1.3.0</version>
        </dependency>
</dependencies>

二、場景實現

1、在閘道器的配置檔案中配置ribbon(負載均衡)和hystrix(熔斷機制)

#熔斷機制
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 6000

#負載均衡
ribbon:
  ConnectionTimeout: 500
  ReadTimeout: 2000
#埠
server:
  port: 8080
spring:
  #該配置檔案中的配置,對應的服務名稱是wc-gateway
  application:
    name: wc-gateway
  profiles:
    active: dev
#服務閘道器配置
zuul:
  host:
    connect-timeout-millis: 60000
    socket-timeout-millis: 60000
  #路由規則
  routes:
    api:
      path: /api/user/**
      serviceId: wc-client-user

其實ribbon的真實值=(ConnectionTimeout+ReadTimeout)*2,該值最好小於hystrix的timeoutInMilliseconds的值,因為如果大於其值會失去負載均衡(ribbon)的重試機會,而直接熔斷

2、驗證負載均衡

因為zuul下自帶了hystrix,ribbon相關jar包,所有現在已經實現了負載均衡和熔斷機制,接下來進行驗證

在client服務下編寫controller,測試負載均衡

package top.wingcloud.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: linjie
 * @description: 使用者服務請求處理控制器
 * @create: 2018/11/06 09:16
 */
@RestController
public class UserController {
    @Value("${server.port}")
    private int port;

    @RequestMapping("index")
    public String index(){
        return "Hello World!"+port;
    }
}

依次啟動註冊中心、配置中心、client服務、修改埠再次啟動client服務、服務閘道器

根據閘道器的路由,訪問同一個路由,發現啟動的兩個不同埠的client服務交替執行

出現該情況即實現了負載均衡

3、驗證熔斷機制

在閘道器服務中需要寫ZuulFallbackProvider的實現類

package top.wingcloud.filter;

import org.springframework.cloud.netflix.zuul.filters.route.ZuulFallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author: linjie
 * @description:錯誤攔截回顯,熔斷
 * @create: 2018/10/11 20:01
 */
@Component
public class ApiFallbackProvider implements ZuulFallbackProvider{

    @Override
    public String getRoute() {
        //設定熔斷的服務名
        //如果是所有服務則設定為*
        return "wc-client-user";
    }

    @Override
    public ClientHttpResponse fallbackResponse() {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return 200;
            }

            @Override
            public String getStatusText() throws IOException {
                return "{code:0,message:service error =_=}";
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream(getStatusText().getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                return headers;
            }
        };
    }
}

這個時候關閉client所有服務,再次訪問之前的閘道器路由

出現了getStatusText()中的提示,即實現了熔斷機制

好了,zuul下的負載均衡和熔斷已經實現,時間不早了,趕緊睡覺!