zoukankan      html  css  js  c++  java
  • springcloud+zuul+swagger2之微服务通过网关进行分发

    因公司技术架构需要,我从zk+dubbo+springboot开始接触springcloud一系列架构。首先接触到新东西,我内心是希望得到学习的,毕竟技多不压身,更何况用springcloud也不是新技术了[苦瓜脸]。此文章主要讲述整个配置关键点,其他细节请找我家彦宏。

    进入正题:用zuul网关的目的,就我目前来看是为了让几个服务对外保证一个域名请求,得到请求后网关进行转发到各个服务上。第一步准备两个及以上的微服务,这些都是注册到eureka上的服务名称

     1.user-serive

         user-service服务里的controller1: api/v1/user/userAddress

                                           controller2:api/v1/user/userCompany

     2.order-service:如上

     3.zuul-service(网关服务)

     第二步,在zuul服务里配置转发策略:

      创建zuul模块的功能,就忽略不讲了,都可以在网上搜到。主要是一些配置application.yml的地方,我粘贴出来:

    zuul:
      routes:
        order-service:
          path: /**/order/** 此处一定要这样写,不要写成/order/**;否则在进行转发的时候,请求不通;会在转发的时候,前面需要手动加上order,再连接api/v1才能请求;
        user-service:
          path: /**/user/**

     在请求转发的过程中,第一次请求的时候,zuul会超时,原因如下:(如果大家想仔细了解,可去深究zuul机制)

    这是因为zuul采用了懒加载机制,第一次访问的时候才会加载某些类,而不是启动时就加载了,由于默认的时间原本就比较短,加载这些类又需要一些时间,这就造成超时了。

    解决方式是在application.yml中配置:

    zuul:
    host:(跟以上routes同等级) connect-timeout-millis: 15000 #HTTP连接超时大于Hystrix的超时时间 socket-timeout-millis: 60000 #socket超时
    ribbon: (跟zuul同等级)       #设置ribbon的超时时间小于zuul的超时时间
      ReadTimeout: 10000
      ConnectTimeout: 10000

      此时,如果有请求地址中有order的,就会转发到order-service去请求;如果地址中有user的,则会转发到user-service请求,成功转发。

    ————————————————————————————————————————————————————————

    接下来贴一下swagger关联代码

    添加swagger的方式:

    1.在zuul服务中pom.xml加入:

    <!-- swagger2 依赖 -->
    <dependency>
       <groupId>io.springfox</groupId>
       <artifactId>springfox-swagger2</artifactId>
       <version>2.6.0</version>
    </dependency>
    <dependency>
       <groupId>io.springfox</groupId>
       <artifactId>springfox-swagger-ui</artifactId>
       <version>2.6.0</version>
    </dependency>
    <dependency>
       <groupId>com.github.xiaoymin</groupId>
       <artifactId>swagger-bootstrap-ui</artifactId>
       <version>1.8.1</version>
    </dependency>

    2.新建swagger配置类:

    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {
    
        @Autowired
        private DiscoveryClientRouteLocator discoveryClientRouteLocator;
        @Bean
        public Docket buildDocket() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(buildApiInfo()) // .apiInfo(apiInfo())
                    .select()
                    .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                    .paths(PathSelectors.any())
                    .build();
        }
    
        private ApiInfo buildApiInfo() {
            return new ApiInfoBuilder()
                    .title("对接接口文档")
                    .description("相关后台接口")
                    .contact("程序猿")
                    .version("1.0")
                    .build();
        }

     3.新建文档配置类

    @Component
    @Primary
    public class DocumentationConfig implements SwaggerResourcesProvider{
    
        private final RouteLocator routeLocator;
    
        @Autowired
        private DiscoveryClient discoveryClient;
    
        @Value("${spring.application.name}")
        private String applicationName;
    
        public DocumentationConfig(RouteLocator routeLocator) {
            this.routeLocator = routeLocator;
        }
       // 自动获取系统配置的路由资源集合
       @Override
       public List<SwaggerResource> get() {
           List<SwaggerResource> resources = new ArrayList<>();
           // 排除自身,将其他的服务添加进去
           discoveryClient.getServices().stream().filter(s -> !s.equals(applicationName)).forEach(name -> {
               Optional<ServiceInstance> instanceOptional = discoveryClient.getInstances(name).stream().findFirst();
               if (instanceOptional.isPresent() && instanceOptional.get().getMetadata().containsKey("context-path")) {
                   String contexPath = instanceOptional.get().getMetadata().get("context-path");
                   resources.add(swaggerResource(name, "/" + name + contexPath + "/v2/api-docs", "2.0"));
               } else {
                   resources.add(swaggerResource(name, "/" + name + "/v2/api-docs", "2.0"));
               }
    
           });
           return resources;
       }
    
        private SwaggerResource swaggerResource(String name, String location, String version) {
            SwaggerResource swaggerResource = new SwaggerResource();
            swaggerResource.setName(name);
            swaggerResource.setLocation(location);
            swaggerResource.setSwaggerVersion(version);
            return swaggerResource;
        }
    }
    

    ————————————————————————————————————————————————————————

    最后整体效果为:

    注明:

    此文章纯属个人分享,如有不对的地方请大家批评指正。

    解决出来的部分内容也是我在网上搜罗汇集的,仅供参考 

  • 相关阅读:
    唐李问对 简单飞扬
    【关键字】Javascript js 身份证号码 检测 规则 18位 15位 简单飞扬
    司马法 简单飞扬
    实现身份证的15位转18位 简单飞扬
    JAVA验证身份证号码 简单飞扬
    页面验证的类型 简单飞扬
    模拟MSN和QQ的上线提示效果 区别IE和FF浏览器 简单飞扬
    孙子兵法 简单飞扬
    吴子 简单飞扬
    C# WPF MVVM 实战 2.1
  • 原文地址:https://www.cnblogs.com/sunnyguo/p/11826656.html
Copyright © 2011-2022 走看看