76

springboot~zuul实现网关

 6 years ago
source link: http://www.cnblogs.com/lori/p/9811526.html?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

网关在微服务里的角色

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

  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这个键值对!


Recommend

  • 154
    • blueskykong.com 7 years ago
    • Cache

    微服务网关netflix-zuul | Aoho's Blog

    引言:前面一个系列文章介绍了认证鉴权与API权限控制在微服务架构中的设计与实现 ,好多同学询问有没有完整的demo项目,笔者回答肯定有的。由于之前系列文章侧重讲解了权限前置,所以近期补上完整的后置项目,但是这最好有一个完整的微服务调用。本文主要讲下API网...

  • 394
    • dockone.io 6 years ago
    • Cache

    高并发下-Zuul参数调优

    What is Zuul? 官方介绍: Zuul is the front door for all requests from devices and web sites to the backend of the Netflix streaming application.As an edge service application, Zuul is built to en...

  • 50
    • 微信 mp.weixin.qq.com 5 years ago
    • Cache

    Zuul中聚合Swagger的坑

  • 13

    随着业务的扩展,微服务会不对增加,相应的其对外开放的 API 接口也势必增多,这不利于前端的调用以及不同场景下数据的返回,因此,我们通常都需要设计一个 API 网关作为一个统一的 API 入口,来组合一个或多个内部 API。 二、简单介绍 2.1 AP...

  • 28

    基于 ServiceComb 和 SpringCloud Zuul 快速构建微服务系统 2 分钟 阅读 基于ServiceComb和Zuul实现微服务网关,如此一来用户只需要专注实现其业务需求。 本文将以...

  • 10

    至此,已实现基于Eureka的服务发现,基于Ribbon的负载均衡,Feign也为我们提供了很不错的远程调用能力,使用Hystrix后,高并发场景下应用也不会被别人拖死——咱们的微服务架构已经日趋完善! 然而,迄今为止,只讨论了微服务之间的调用,尚没讨论如何应对...

  • 11

    Spring Cloud之Finchley版学习(十八)-Zuul深入 作者: wencst 分类: JAVA,微服...

  • 13

    网关 zuul 与 spring-cloud gateway的区别 用代码保护地球, AI 和 IoT 世界的工程师们准备好了吗?...

  • 10

    Part 5 : Spring Cloud Zuul Proxy as API GatewaySkip to contentShare this:In mic...

  • 4
    • juejin.cn 2 years ago
    • Cache

    网关 Zuul 科普

    为什么要使用网关? 不同的微服务一般会有不同的网络地址,而外部客户端(例如手机 APP)可能需要调用多个服务的接口才能完成一个业务需求。例如一个电影购票的手机 APP,可能会调用多个微服务的接口,才能完成一次购票的业务流程,如下图所示。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK