广告
返回顶部
首页 > 资讯 > 后端开发 > Python >spring-gateway网关聚合swagger实现多个服务接口切换的示例代码
  • 534
分享到

spring-gateway网关聚合swagger实现多个服务接口切换的示例代码

2024-04-02 19:04:59 534人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

前提条件 微服务已经集成了swagger,并且注册进了Nacos。 gateway配置 package com.zmy.SpringCloud.config; import org

前提条件

微服务已经集成了swagger,并且注册进了Nacos

gateway配置

package com.zmy.SpringCloud.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.WEB.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.*;


@Component
public class MySwaggerResourceProvider implements SwaggerResourcesProvider {
    
    private static final String SWAGGER2URL = "/v2/api-docs";

    
    private final RouteLocator routeLocator;

    
    @Value("${spring.application.name}")
    private String self;

    @Autowired
    public MySwaggerResourceProvider(RouteLocator routeLocator) {
        this.routeLocator = routeLocator;
    }

    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> resources = new ArrayList<>();
        List<String> routeHosts = new ArrayList<>();
        // 获取所有可用的host:serviceId
        routeLocator.getRoutes().filter(route -> route.getUri().getHost() != null)
                .filter(route -> !self.equals(route.getUri().getHost()))
                .subscribe(route -> routeHosts.add(route.getUri().getHost()));

        // 记录已经添加过的server
        Set<String> dealed = new HashSet<>();
        routeHosts.forEach(instance -> {
            // 拼接url
            String url = "/" + instance.toLowerCase() + SWAGGER2URL;
            if (!dealed.contains(url)) {
                dealed.add(url);
                SwaggerResource swaggerResource = new SwaggerResource();
                swaggerResource.setUrl(url);
                swaggerResource.setName(instance);
                resources.add(swaggerResource);
            }
        });
        return resources;
    }
}

package com.zmy.sprinGCloud.config.swagger.controller;

import com.zmy.springcloud.config.MySwaggerResourceProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.Http.httpstatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.swagger.web.*;

import java.util.List;


@RestController
@RequestMapping("/swagger-resources")
public class SwaggerResourceController {
    private MySwaggerResourceProvider swaggerResourceProvider;

    @Autowired
    public SwaggerResourceController(MySwaggerResourceProvider swaggerResourceProvider) {
        this.swaggerResourceProvider = swaggerResourceProvider;
    }

    @RequestMapping(value = "/configuration/security")
    public ResponseEntity<SecurityConfiguration> securityConfiguration() {
        return new ResponseEntity<>(SecurityConfigurationBuilder.builder().build(), HttpStatus.OK);
    }

    @RequestMapping(value = "/configuration/ui")
    public ResponseEntity<UiConfiguration> uiConfiguration() {
        return new ResponseEntity<>(UiConfigurationBuilder.builder().build(), HttpStatus.OK);
    }

    @RequestMapping
    public ResponseEntity<List<SwaggerResource>> swaggerResources() {
        return new ResponseEntity<>(swaggerResourceProvider.get(), HttpStatus.OK);
    }
}

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!--swagger生成API文档-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
    <exclusions>
        <exclusion>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-models</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-models</artifactId>
    <version>1.5.22</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
<!--nacos-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
server:
  port: 9527
spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      routes:
        - id: seata-storage-service
          uri: lb://seata-storage-service
          predicates:
            - Path=/seata-storage-service/**         # 断言,相匹配的进行路由
          filters:
            - StripPrefix=1
        - id: seata-account-service
          uri: lb://seata-account-service
            - Path=/seata-account-service/**
      discovery:
        locator:
          enabled: true #开启从注册中心动态创建路由的功能,利用微服务名进行路由
    nacos:
        server-addr: localhost:8848

- StripPrefix=1是必须配置的,跳过- Path的第一段路径。

http://localhost:2003/v2/api-docs 这个是正确的swagger数据请求地址。不加- StripPrefix=1的话,swagger在请求数据时候会请求http://localhost:2003/seata-account-service/v2/api-docs,这样就会请求不到数据。

在这里插入图片描述

如果不加- StripPrefix=1,也有其他的解决方案,可以在微服务提供者中配置服务上下文路径

server:
  servlet:
    context-path: /seata-order-service

注意网关的拦截器,不要将swagger请求拦截掉。

到此这篇关于spring-gateway网关聚合swagger实现多个服务接口切换的文章就介绍到这了,更多相关spring-gateway网关聚合swagger内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: spring-gateway网关聚合swagger实现多个服务接口切换的示例代码

本文链接: https://www.lsjlt.com/news/141456.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作