微服务 springcloud 08.zuul框架,API网关,整合ribbon和hystrix框架

01.zuul是作为springcloud中的一个网关框架来使用的。
zuul API 网关,为微服务应用提供统一的对外访问接口。
zuul 还提供过滤器,对所有微服务提供统一的请求校验。
在项目中的位置:
微服务 springcloud 08.zuul框架,API网关,整合ribbon和hystrix框架_第1张图片
02.新建 sp11-zuul 项目
微服务 springcloud 08.zuul框架,API网关,整合ribbon和hystrix框架_第2张图片
微服务 springcloud 08.zuul框架,API网关,整合ribbon和hystrix框架_第3张图片
03.pom.xml
需要添加 sp01-commons 依赖



	4.0.0
	
		org.springframework.boot
		spring-boot-starter-parent
		2.3.1.RELEASE
		 
	
	cn.tedu
	sp11-zuul
	0.0.1-SNAPSHOT
	sp11-zuul
	Demo project for Spring Boot
	
		1.8
		Hoxton.SR12
	
	
		
			org.springframework.cloud
			spring-cloud-starter-netflix-eureka-client
		
		
			org.springframework.cloud
			spring-cloud-starter-netflix-zuul
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
			
				
					org.junit.vintage
					junit-vintage-engine
				
			
		
		
			cn.tedu
			sp01-commons
			0.0.1-SNAPSHOT
		
	
	
		
			
				org.springframework.cloud
				spring-cloud-dependencies
				${spring-cloud.version}
				pom
				import
			
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	


04.application.yml
zuul 路由配置可以省略,缺省以服务 id 作为访问路径


spring:
  application:
    name: zuul
    
server:
  port: 3001
  
eureka:
  client:
    service-url:
      defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka

zuul:
  routes:
    item-service: /item-service/**
    user-service: /user-service/**
    order-service: /order-service/**

zuul上的routes都是从eureka中获取的
05.主程序
添加 @EnableZuulProxy 和 @EnableDiscoveryClient 注解

package cn.tedu.sp11;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

@EnableZuulProxy
@EnableDiscoveryClient
@SpringBootApplication
public class Sp11ZuulApplication {

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

}

zuul + ribbon 负载均衡
01.pom.xml 添加 spring-retry 依赖


	  org.springframework.retry
	  spring-retry

02.配置 zuul 开启重试,并配置 ribbon 重试参数
需要开启重试,默认不开启

spring:
  application:
    name: zuul
    
server:
  port: 3001
  
eureka:
  client:
    service-url:
      defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka

zuul:
  retryable: true
  routes:
    item-service: /item-service/**
    user-service: /user-service/**
    order-service: /order-service/**
    
ribbon:
  ConnectTimeout: 1000
  ReadTimeout: 1000
  MaxAutoRetriesNextServer: 1
  MaxAutoRetries: 1

zuul + hystrix 降级
01.创建降级类
getRoute() 方法中指定应用此降级类的服务id,星号或null值可以通配所有服务
02.ItemServiceFallback

package cn.tedu.sp11.fallback;

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

import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
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 cn.tedu.web.util.JsonResult;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class ItemServiceFallback implements FallbackProvider {
	@Override
	public String getRoute() {
	    //当执行item-service失败,
	    //应用当前这个降级类
		return "item-service";
		//星号和null都表示所有微服务失败都应用当前降级类
		//"*"; //null;
	}

    //该方法返回封装降级响应的对象
    //ClientHttpResponse中封装降级响应
	@Override
	public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return response();
	}

	private ClientHttpResponse response() {
        return new ClientHttpResponse() {
            //下面三个方法都是协议号
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }
            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.OK.value();
            }
            @Override
            public String getStatusText() throws IOException {
                return HttpStatus.OK.getReasonPhrase();
            }

            @Override
            public void close() {
            }

            @Override
            public InputStream getBody() throws IOException {
            	log.info("fallback body");
            	String s = JsonResult.err().msg("后台服务错误").toString();
                return new ByteArrayInputStream(s.getBytes("UTF-8"));
            }

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

03.OrderServiceFallback

package cn.tedu.sp11.fallback;

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

import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
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 cn.tedu.web.util.JsonResult;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class OrderServiceFallback implements FallbackProvider {
	@Override
	public String getRoute() {
		return "order-service"; //"*"; //null;
	}

	@Override
	public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return response();
	}

	private ClientHttpResponse response() {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }
            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.OK.value();
            }
            @Override
            public String getStatusText() throws IOException {
                return HttpStatus.OK.getReasonPhrase();
            }

            @Override
            public void close() {
            }

            @Override
            public InputStream getBody() throws IOException {
            	log.info("fallback body");
            	String s = JsonResult.err().msg("后台服务错误").toString();
                return new ByteArrayInputStream(s.getBytes("UTF-8"));
            }

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

04.降低 hystrix 超时时间,以便测试降级
在aplication.yml中:

hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 500

zuul + hystrix 数据监控
01.暴露 hystrix.stream 监控端点
zuul 已经包含 actuator 依赖

management:
  endpoints:
    web:
      exposure:
        include: hystrix.stream

启动服务,查看暴露的监控端点
http://localhost:3001/actuator
http://localhost:3001/actuator/hystrix.stream
02.
启动 sp08-hystrix-dashboard,填入 zuul 的监控端点路径,开启监控
http://localhost:4001/hystrix
填入监控端点:
http://localhost:3001/actuator/hystrix.stream
微服务 springcloud 08.zuul框架,API网关,整合ribbon和hystrix框架_第4张图片
必须通过zuul网关访问后台服务才会产生监控数据
http://localhost:3001/item-service/35

zuul + turbine 聚合监控
01.修改 turbine 项目,聚合 zuul 服务实例

spring:
  application:
    name: turbine
    
server:
  port: 5001
  
eureka:
  client:
    service-url:
      defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka
      
turbine:
  app-config: order-service,zuul
  cluster-name-expression: new String("default")

02.使用hystrix仪表盘, 对 turbine 监控端点进行监控, 此端点聚合了订单服务和zull网关服务的监控数据

http://localhost:5001/turbine.stream微服务 springcloud 08.zuul框架,API网关,整合ribbon和hystrix框架_第5张图片

你可能感兴趣的:(spring,cloud,微服务,ribbon)