springboot~zuul实现网关

栏目: Java · 发布时间: 7年前

内容简介:在微服务架构体系里,网关是非常重要的一个环节,它主要实现了一些功能的统一处理,包括了:1 添加依赖2 添加yml

网关在微服务里的角色

在微服务架构体系里,网关是非常重要的一个环节,它主要实现了一些功能的统一处理,包括了:

  1. 统一授权
  2. 统一异常处理
  3. 路由导向
  4. 跨域处理
  5. 限流

实践一下

1 添加依赖

dependencies {
    implementation('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client')
    implementation('org.springframework.cloud:spring-cloud-starter-netflix-zuul')
    testImplementation('org.springframework.boot:spring-boot-starter-test')
    implementation('com.marcosbarbero.cloud:spring-cloud-zuul-ratelimit:1.3.2.RELEASE')
}

2 添加yml

server:
  port: 8300
spring:
  application:
    name: microservice-gateway-zuul
eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:6761/eureka
  instance:
    ip-address: true

zuul:
 routes:
    users:
       path: /lind/** #以lind开头的路径被重定向到lind服务
       serviceId: lind
 add-host-header: true #显示真实的http头
 retryable: false #关闭Hystrix的重试功能
 ratelimit:
    enabled: true
   #  repository: REDIS
    behind-proxy: true
    policies:
       users:
         limit: 5 #限流,每分钟请求5次
         refresh-interval: 60
         type:
           - user
           - origin
           - url
         #       url类型的限流就是通过请求路径区分
         #       origin是通过客户端IP地址区分
         #       user是通过授权用户进行区分,也包括匿名用户

3 添加实现代码

http拦截器,获取用户ID,为子服务进行传递

public class PreRequestLogFilter extends ZuulFilter {
  private static final Logger logger = LoggerFactory.getLogger(PreRequestLogFilter.class);
  private final RateLimiter rateLimiter = RateLimiter.create(1000.0);

  @Override
  public Object run() {

    try {
      RequestContext currentContext = RequestContext.getCurrentContext();
      HttpServletResponse response = currentContext.getResponse();
      HttpServletRequest reqeust = currentContext.getRequest();

      currentContext.addZuulRequestHeader("userId","123");//向子系统http头写数据
      currentContext.addZuulRequestHeader("userName","test");

      PreRequestLogFilter.logger.info(
          String.format("send %s request to %s",
              reqeust.getMethod(),
              reqeust.getRequestURL().toString()));

      if (!rateLimiter.tryAcquire()) {
        HttpStatus httpStatus = HttpStatus.TOO_MANY_REQUESTS;
        response.setContentType(MediaType.TEXT_PLAIN_VALUE);
        response.setStatus(httpStatus.value());
        response.getWriter().append(httpStatus.getReasonPhrase());
        currentContext.setSendZuulResponse(false);
        throw new ZuulException(
            httpStatus.getReasonPhrase(),
            httpStatus.value(),
            httpStatus.getReasonPhrase()
        );
      }
    } catch (java.lang.Exception e) {
      ReflectionUtils.rethrowRuntimeException(e);
    }
    return null;

  }

  @Override
  public boolean shouldFilter() {

    // 判断是否需要过滤
    return true;

  }


  @Override

  public String filterType() {

    return FilterConstants.PRE_TYPE;

  }


  @Override

  public int filterOrder() {

    return Ordered.HIGHEST_PRECEDENCE;

  }


}

在主程中注入这个过滤器

@Bean
  public PreRequestLogFilter preRequestLogFilter() {
    return new PreRequestLogFilter();
  }

4 使用它

在URL上通过localhost:8300/users/home 将进行lind服务里的home控制器下,并在http头上写入了userid和username这个键值对!


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

金融数量分析

金融数量分析

郑志勇 / 北京航空航天大学出版社 / 2014-7-1 / CNY 58.00

《金融数量分析——基于MATLAB编程(第3版)》一书中的案例均来源于作者的工作实际,并充分体现“案例的实用性、程序的可模仿性”,程序中附有详细的注释。例如,投资组合管理、KMV模型计算、期权定价模型与数值方法、风险价值VaR的计算等案例程序,读者可以直接使用或根据需要在源代码的基础上修改、完善。 本书共23章。前两章分别对金融市场的基本概况与MATLAB的基础知识进行概述;接下来为20个金......一起来看看 《金融数量分析》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

html转js在线工具
html转js在线工具

html转js在线工具