首页 > 其他分享 >网关Zuul+route+Filter+Fallback+Retry笔记20221202

网关Zuul+route+Filter+Fallback+Retry笔记20221202

时间:2022-12-19 11:06:20浏览次数:45  
标签:网关 Retry Zuul springframework eureka return org import public

一、ek2014
1、pom.xml
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
  </dependency>

2、application.properties
# 应用名称
spring.application.name=eureka

server.port=2013
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.service-url.defaultZone=http://localhost:2013/eureka/
eureka.server.eviction-interval-timer-in-ms=5

 

3、Ek2013Application
@EnableEurekaServer
@SpringBootApplication
public class Ek2013Application {
  public static void main(String[] args) {
    SpringApplication.run(Ek2013Application.class, args);
  }
}

网关Zuul+route+Filter+Fallback+Retry笔记20221202_spring

 

 

网关Zuul+route+Filter+Fallback+Retry笔记20221202_.net_02

 

 

二、Provider2033
1、pom.xml
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

2、application.properties
# 应用名称
spring.application.name=provider2033
# 应用服务 WEB 访问端口
server.port=2033
##eureka
eureka.client.service-url.defaultZone=http://localhost:2013/eureka/
eureka.instance.prefer-ip-address=true
eureka.instance.instance-id=${spring.cloud.client.ip-address}:${server.port}
eureka.instance.lease-renewal-interval-in-seconds=5
eureka.instance.lease-expiration-duration-in-seconds=10

 

3、Provider2033Application
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@EnableDiscoveryClient
@SpringBootApplication
public class Provider2033Application {

       private final Logger logger= (Logger) LoggerFactory.getLogger(FallbackProvider.class);

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

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

  @RequestMapping("/")
  public String home(){    

    logger.info("request tow name");
    try {
      Thread.sleep(1000000);
    }catch (Exception e){
      logger.error("hello tow error",e);
    }
    return "软件老五,端口"+port+" ,this is twn message";

  }

}

 

网关Zuul+route+Filter+Fallback+Retry笔记20221202_ide_03

 

 

 

三、Zull2041
1、pom.xml
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
  </dependency>

  <dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
  </dependency>

2、application.properties

# 应用名称
spring.application.name=zuul2041
server.port=2041

##eureka
eureka.client.service-url.defaultZone=http://localhost:2013/eureka/
eureka.client.registry-fetch-interval-seconds=30
eureka.instance.lease-renewal-interval-in-seconds=15
eureka.instance.lease-expiration-duration-in-seconds=45

#####route id: api-provider
#####service-id:provider2033
##http://localhost:2033  ==> http://localhost:2041/provider

######1、第一种
##-----zuul.routes.api-provider.path=/provider/**
##-----zuul.routes.api-provider.service-id=provider2033

######2、第二种 简易配置(route id、service-id一样)
####若route id、service-id:一样 provider2033
zuul.routes.provider2033.path=/provider/**
##zuul.routes.api-provider.service-id=provider2033
####

 

 

3、Zull2041Application
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

@EnableZuulProxy
@EnableEurekaClient
@SpringBootApplication
public class Zull2041Application {

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

  //***********MyZullFilter第一种@Bean启用
  //MyZullFilter的@Component 注解掉
  @Bean
  public MyZullFilter myZullFilter(){
    return new MyZullFilter();
  }

  //***********MyZullFilter第二种的@Component启用
  //Zull2041Application的@Bean 注解掉

}

4、MyZullFilter

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
public class MyZullFilter extends ZuulFilter {

每秒放多少个token(10个)
    private static final RateLimiter RATE_LIMITER=RateLimiter.create(10);
    /**
    * 过滤类型
    * @return
    */
    @Override
    public String filterType() {
      return "pre";
    }

    /**
    * 请求过滤顺序
    * @return
    */
    @Override
    public int filterOrder() {
      return 0;
    }

    /**
    * 判断过滤器是否生效
    * @return
    */
    @Override
    public boolean shouldFilter() {
      return true;
    }

    @Override
    public Object run() throws ZuulException {
      /* if(!RATE_LIMITER.tryAcquire()){
        System.out.println("限流.....................");
      }*/

      //获取token参数
      RequestContext rc=RequestContext.getCurrentContext();
      if(!RATE_LIMITER.tryAcquire()) {
        rc.setSendZuulResponse(false);
        rc.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
        System.out.println("限流.....................");
      }

      HttpServletRequest request=rc.getRequest();

token");
      if(token!=null){
        return null;
      }
      //表示不进行路由
      rc.setSendZuulResponse(false);
      rc.setResponseStatusCode(401);
      try {
        rc.getResponse().setContentType("text/html;charset=utf-8");
        rc.getResponse().getWriter().write("没有传递正确参数,请校验后重试~");
      }catch (IOException e){
        e.printStackTrace();
      }
      return null;
    }

}

 

网关Zuul+route+Filter+Fallback+Retry笔记20221202_.net_04

 

 

网关Zuul+route+Filter+Fallback+Retry笔记20221202_spring_05

 

 

网关Zuul+route+Filter+Fallback+Retry笔记20221202_.net_06

 

 

 5、ProducerFallback

  import org.slf4j.Logger;
  import org.slf4j.LoggerFactory;
  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 java.io.ByteArrayInputStream;
  import java.io.IOException;
  import java.io.InputStream;

  /***
  * 熔断处理
  */
  @Component
  public class ProducerFallback implements FallbackProvider {
    private final Logger logger= (Logger) LoggerFactory.getLogger(FallbackProvider.class);

service-id:provider2033
    @Override
    public String getRoute() {
      return "provider2033";
    }

    public ClientHttpResponse fallbackResponse() {
      return new ClientHttpResponse(){

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

        @Override
        public InputStream getBody() throws IOException {
          return new ByteArrayInputStream("The service is unavailable.".getBytes());
        }

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

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

        @Override
        public String getStatusText() throws IOException {
          return "OK";
        }

        @Override
        public void close() {

        }
      };
  }

  @Override
  public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
    if(cause!=null&&cause.getCause()!=null){
      String reason=cause.getCause().getMessage();
      logger.info("Exception{}"+reason);
    }
    return fallbackResponse();
  }
}

 

 

网关Zuul+route+Filter+Fallback+Retry笔记20221202_.net_07

 

 6、路由重启

网关Zuul+route+Filter+Fallback+Retry笔记20221202_ide_08

 

 

网关Zuul+route+Filter+Fallback+Retry笔记20221202_spring_09

 

 

 

 

四、Jmeter测试

测限流

网关Zuul+route+Filter+Fallback+Retry笔记20221202_spring_10

 

 

网关Zuul+route+Filter+Fallback+Retry笔记20221202_.net_11

 

 

网关Zuul+route+Filter+Fallback+Retry笔记20221202_spring_12

 

标签:网关,Retry,Zuul,springframework,eureka,return,org,import,public
From: https://blog.51cto.com/smallfa/5951512

相关文章

  • PLC远程上下载程序,一台物联网网关轻松解决
    在工业现场环境中,PLC越来越多的被用于生产流程、自动化控制等场景,但在高效率生产活动和自动化要求不断变化的当下,PLC的程序编程也需要升级提升。工程师常常需要升级或者修复......
  • 认证管理(锐捷网关篇)
    大家好,我是小杜,明天又是周末了,按照师傅的“专政”──不允许周末来公司,可以去下现场看下,只能“勉为其难”在家好好休息了,呵呵呵......轻轻拍了下自己嘴巴来回神,......
  • 公司新来一个同事,把网关系统设计的炉火纯青!(万能通用,稳的一批。。)
    来源:developer.aliyun.com/article/889271本文准备围绕七个点来讲网关,分别是网关的基本概念、网关设计思路、网关设计重点、流量网关、业务网关、常见网关对比,对基础概念......
  • DGIOT边缘主机功能——6USB串口替代普通dtu/网关的设备接入
    [小迪导读]:dgiot边缘主机自带6个USB口、2个RS232串口以及2个网口,可用组态对边缘主机上的USB口、串口和网口等上的外设进行可视化管理,包括如下功能:通过6个USB口外接USB......
  • 罗克韦尔(AB)PLC远程维护连接不上网关怎么办?
    对很多使用罗克韦尔(AB)PLC的工厂来说,PLC具备成熟系统和稳定性能等特点,可以适应厂内设备的控制指令,需要细心保养,认真维护。随着无线通信技术和物联网技术的发展,PLC的数据上云......
  • Gateway服务网关的介绍与使用
    什么是服务网关传统的单体架构中只需要开放一个服务给客户端调用,但是微服务架构中是将一个系统拆分成多个微服务,如果没有网关,客户端只能在本地记录每个微服务的调用地址,当需......
  • 通过服务网格减少对API网关依赖
    微服务和微服务之间有调用关系,所有调用关系都经过API网关,最终的调用链如图1所示。基于API网关的数据转发如图1所示,展示了4个微服务之间的3次调用,可以看出任何服务到服务之......
  • asp.net core 微服务网关示例 ocelot gateway Demo
    ocelotasp.netcore微服务gateway介绍https://ocelot.readthedocs.io/en/latest/introduction/gettingstarted.html 1.新建asp.netcorewebapi空项目AProject,nug......
  • BL110网关远程监测充电桩断网故障解决方案
    在碳中和等因素的影响下,燃油车逐步退出市场,新能源汽车逐步替代燃油车市场,获得了爆发性增长的市场空间。近年来,中国新能源汽车市场保持高速增长,新能源汽车当前的保有量、增......
  • Ocelot API网关的实现剖析
    在微软TechSummit2017大会上和大家分享了一门课程《.NETCore在腾讯财付通的企业级应用开发实践》,其中重点是基于ASP.NETCore打造可扩展的高性能企业级API网关,以开源的......