当前位置: 首页 > news >正文

Spring Cloud Gateway 集成 Nacos、Knife4j

目录

  • 1、gateway网关配置
    • 1.1 pom 配置
    • 2.2 配置文件
    • 1.3 yaml 配置
  • 2、其他服务配置
    • 2.1 pom 配置
    • 2.2 配置文件
    • 2.3 yaml 配置
  • 3、界面访问
  • 4、其他

官方文档地址:Spring Cloud Gateway集成Knife4j
官方完整源码:https://gitee.com/xiaoym/swagger-bootstrap-ui-demo
自己搭建的源码地址:https://gitee.com/sheng-wanping/spring-boot-gateway

其实Knife4j官方文档写的很全,自己也是按照文档搭建的,这里记录一下自己的搭建过程:
由于公司使用的springboot版本较低,是2.1.3.RELEASE,因此其他组件使用了对应较低版本。

  • springboot版本2.1.3.RELEASE
  • nacos 版本2.1.4.RELEASE
  • gateway版本2.1.0.RELEASE
  • knife4j版本2.0.2

springboot 其他版本可以参考:spring-cloud-alibaba 版本对应说明

Spring Cloud Alibaba VersionSpring Cloud VersionSpring Boot Version
2022.0.0.0-RC*Spring Cloud 2022.0.03.0.0
2021.0.4.0*Spring Cloud 2021.0.42.6.11
2021.0.1.0Spring Cloud 2021.0.12.6.3
2021.1Spring Cloud 2020.0.12.4.2
2.2.10-RC1*Spring Cloud Hoxton.SR122.3.12.RELEASE
2.2.9.RELEASESpring Cloud Hoxton.SR122.3.12.RELEASE
2.2.8.RELEASESpring Cloud Hoxton.SR122.3.12.RELEASE
2.2.7.RELEASESpring Cloud Hoxton.SR122.3.12.RELEASE
2.2.6.RELEASESpring Cloud Hoxton.SR92.3.2.RELEASE
2.2.1.RELEASESpring Cloud Hoxton.SR32.2.5.RELEASE
2.2.0.RELEASESpring Cloud Hoxton.RELEASE2.2.X.RELEASE
2.1.4.RELEASESpring Cloud Greenwich.SR62.1.13.RELEASE
2.1.2.RELEASESpring Cloud Greenwich2.1.X.RELEASE
2.0.4.RELEASE(停止维护,建议升级)Spring Cloud Finchley2.0.X.RELEASE
1.5.1.RELEASE(停止维护,建议升级)Spring Cloud Edgware1.5.X.RELEASE

1、gateway网关配置

1.1 pom 配置

<!-- nacos 配置和注册中心 -->
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency><!-- Gateway 网关相关 -->
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId>
</dependency><!-- knife4j -->
<dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-spring-boot-starter</artifactId>
</dependency>

2.2 配置文件

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.support.NameUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;import java.util.ArrayList;
import java.util.List;@Slf4j
@Component
@Primary
@AllArgsConstructor
public class SwaggerResourceConfig implements SwaggerResourcesProvider {private final RouteLocator routeLocator;private final GatewayProperties gatewayProperties;@Overridepublic List<SwaggerResource> get() {List<SwaggerResource> resources = new ArrayList<>();List<String> routes = new ArrayList<>();routeLocator.getRoutes().subscribe(route -> routes.add(route.getId()));gatewayProperties.getRoutes().stream().filter(routeDefinition -> routes.contains(routeDefinition.getId())).forEach(route -> {route.getPredicates().stream().filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName())).forEach(predicateDefinition -> resources.add(swaggerResource(route.getId(),predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0").replace("**", "v2/api-docs"))));});return resources;}private SwaggerResource swaggerResource(String name, String location) {log.info("name:{},location:{}",name,location);SwaggerResource swaggerResource = new SwaggerResource();swaggerResource.setName(name);swaggerResource.setLocation(location);swaggerResource.setSwaggerVersion("2.0");return swaggerResource;}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import springfox.documentation.swagger.web.*;
import java.util.Optional;/*** @author xiaoymin* 2020年10月29日 18:38:01*/
@RestController
public class SwaggerHandler {@Autowired(required = false)private SecurityConfiguration securityConfiguration;@Autowired(required = false)private UiConfiguration uiConfiguration;private final SwaggerResourcesProvider swaggerResources;@Autowiredpublic SwaggerHandler(SwaggerResourcesProvider swaggerResources) {this.swaggerResources = swaggerResources;}@GetMapping("/swagger-resources/configuration/security")public Mono<ResponseEntity<SecurityConfiguration>> securityConfiguration() {return Mono.just(new ResponseEntity<>(Optional.ofNullable(securityConfiguration).orElse(SecurityConfigurationBuilder.builder().build()), HttpStatus.OK));}@GetMapping("/swagger-resources/configuration/ui")public Mono<ResponseEntity<UiConfiguration>> uiConfiguration() {return Mono.just(new ResponseEntity<>(Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build()), HttpStatus.OK));}@GetMapping("/swagger-resources")public Mono<ResponseEntity> swaggerResources() {return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK)));}
}
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;/*** @author fsl* @description: SwaggerHeaderFilter* @date 2019-06-0310:47*/
@Component
public class SwaggerHeaderFilter extends AbstractGatewayFilterFactory {private static final String HEADER_NAME = "X-Forwarded-Prefix";private static final String URI = "/v2/api-docs";@Overridepublic GatewayFilter apply(Object config) {return (exchange, chain) -> {ServerHttpRequest request = exchange.getRequest();String path = request.getURI().getPath();if (!StringUtils.endsWithIgnoreCase(path,URI )) {return chain.filter(exchange);}String basePath = path.substring(0, path.lastIndexOf(URI));ServerHttpRequest newRequest = request.mutate().header(HEADER_NAME, basePath).build();ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();return chain.filter(newExchange);};}
}

1.3 yaml 配置

application.yaml 主要是网关路由和跨域配置

spring:cloud:# Spring Cloud Gateway 配置项,对应 GatewayProperties 类gateway:# 路由配置项,对应 RouteDefinition 数组routes:- id: byzq-wq-api # 路由的编号uri: lb://byzq-wq # 根据服务名找predicates:- Path=/byzq-wq/** # 映射到对应路径filters:- StripPrefix=1 # 删除第一个路径段 /byzq-wq/api -> /api- id: byzq-yc-api # 路由的编号uri: lb://byzq-ycpredicates:- Path=/byzq-yc/**filters:- StripPrefix=1# 全局跨域配置globalcors:cors-configurations: # 跨域配置列表'[/**]': # 匹配所有路径allowed-headers: "*" # 允许的请求头,*表示允许所有allowed-methods: # 允许的请求方法列表- GET- POST- PUT- DELETE- OPTIONSallowed-origins: "*" # 允许的请求来源,*表示允许所有exposed-headers: # 暴露的响应头列表- Authorization- Content-Typeallow-credentials: true # 是否允许凭证传递,true表示允许

bootstrap.yaml 主要是nacos配置

注: nacos服务必须配置到bootstrap.yaml 里面才能被正确加载,因为执行顺序:bootstrap.yaml > ApplicationContext > application.yaml

server:port: 9999# 需要在ApplicationContext创建之前加载配置文件
spring:application:name: byzq-gatewaycloud:nacos:# nacos 服务注册discovery:server-addr: 127.0.0.1:8848namespace: byzq-local # 命名空间# nacos 配置中心config:server-addr: 127.0.0.1:8848namespace: byzq-local # 命名空间group: DEFAULT_GROUP # 使用的 nacos 配置分组,默认为 DEFAULT_GROUPfile-extension: yaml # 使用的 nacos 配置集的 dataId 的文件拓展名,默认为 properties

2、其他服务配置

2.1 pom 配置

<!-- nacos 配置和注册中心 -->
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency><!-- springboot -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency><!-- Swagger 2 -->
<dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-micro-spring-boot-starter</artifactId>
</dependency>

2.2 配置文件

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;@Configuration
@EnableSwagger2
public class SwaggerConfig {@Value("${swagger.enable}")private Boolean enable;@Beanpublic Docket api() {return new Docket(DocumentationType.SWAGGER_2).enable(enable).apiInfo(apiInfo()).select()//.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).apis(RequestHandlerSelectors.basePackage("org.example.controller")) // 替换为你的controller包路径.paths(PathSelectors.any()).build();}private ApiInfo apiInfo() {return new ApiInfoBuilder().title("巴渝制气-扬尘") // API文档标题.description("巴渝制气-扬尘接口文档") // API文档描述.version("1.0") // API版本//.contact(new Contact("Your Name", "http://www.yourcompany.com/contact", "your.email@example.com")) // 维护者信息//.termsOfServiceUrl("http://www.yourcompany.com/terms") // 服务条款URL.license("Apache 2.0") // 许可证.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html") // 许可证URL.build();}}

2.3 yaml 配置

bootstrap.yaml 配置如下

spring:application:name: byzq-yc# 需要在ApplicationContext创建之前加载配置文件cloud:nacos:# nacos 服务注册discovery:server-addr: 127.0.0.1:8848namespace: byzq-local # 命名空间# nacos 配置中心config:server-addr: 127.0.0.1:8848namespace: byzq-local # 命名空间group: DEFAULT_GROUP # 使用的 nacos 配置分组,默认为 DEFAULT_GROUPfile-extension: yaml # 使用的 nacos 配置集的 dataId 的文件拓展名,默认为 propertiesserver:port: 8082# 关闭swagger设置为false
swagger:enable: true

3、界面访问

启动服务访问 http://localhost:9999/doc.html 应该是能正常访问的。
在这里插入图片描述
如果你需要一套关于gateway+nacos+knife4j的项目可以看看的源码 https://gitee.com/sheng-wanping/spring-boot-gateway 里面还包括了 API网关权限校验、用户接口权限、单点登录,(因为公司要求轻量级因此没有引入spring security 和 jwt)如果觉得有帮到你的话可以帮忙点个 star,感谢!有什么疑问可以评论区留言或者私信。

4、其他

SpringBoot 集成 Nacos

相关文章:

  • 计算机网络7——网络安全3 互联网使用的安全协议
  • 网关(Gateway)- 自定义过滤器工厂
  • 基于安卓的虫害识别软件设计--(2)模型性能可视化|混淆矩阵、热力图
  • 【制作100个unity游戏之27】使用unity复刻经典游戏《植物大战僵尸》,制作属于自己的植物大战僵尸随机版和杂交版6(附带项目源码)
  • x264 参考帧管理原理:b_ref_reorder 数组变量
  • Vue:路由管理vue-router
  • 信息标记形式 (XML, JSON, YAML)
  • DeepFace ——用于高级人脸识别算法探索与应用
  • 【Python】Python异步编程
  • FFmpeg 中 Filters 使用文档介绍
  • 纯网络的系统能否定级备案?
  • 易基因:RNA免疫共沉淀测序 (RIP-seq) 技术介绍
  • 【Java数据结构】详解Stack与Queue(二)
  • MTK 平台项目security boot 开启/关闭 及 系统签名流程
  • autowired注解底层实现代码
  • (ckeditor+ckfinder用法)Jquery,js获取ckeditor值
  • 4. 路由到控制器 - Laravel从零开始教程
  • ES6核心特性
  • Git 使用集
  • java2019面试题北京
  • JavaScript-Array类型
  • JavaScript对象详解
  • MySQL数据库运维之数据恢复
  • Object.assign方法不能实现深复制
  • PHP CLI应用的调试原理
  • springMvc学习笔记(2)
  • 阿里中间件开源组件:Sentinel 0.2.0正式发布
  • 初识 webpack
  • 基于OpenResty的Lua Web框架lor0.0.2预览版发布
  • 通过来模仿稀土掘金个人页面的布局来学习使用CoordinatorLayout
  • 消息队列系列二(IOT中消息队列的应用)
  • 学习使用ExpressJS 4.0中的新Router
  • python最赚钱的4个方向,你最心动的是哪个?
  • 树莓派用上kodexplorer也能玩成私有网盘
  • 昨天1024程序员节,我故意写了个死循环~
  • ​软考-高级-系统架构设计师教程(清华第2版)【第9章 软件可靠性基础知识(P320~344)-思维导图】​
  • # Java NIO(一)FileChannel
  • # Maven错误Error executing Maven
  • #{}和${}的区别?
  • (0)Nginx 功能特性
  • (160)时序收敛--->(10)时序收敛十
  • (28)oracle数据迁移(容器)-部署包资源
  • (ISPRS,2023)深度语义-视觉对齐用于zero-shot遥感图像场景分类
  • (二刷)代码随想录第15天|层序遍历 226.翻转二叉树 101.对称二叉树2
  • (十)DDRC架构组成、效率Efficiency及功能实现
  • (五)IO流之ByteArrayInput/OutputStream
  • (一)硬件制作--从零开始自制linux掌上电脑(F1C200S) <嵌入式项目>
  • (已更新)关于Visual Studio 2019安装时VS installer无法下载文件,进度条为0,显示网络有问题的解决办法
  • (转)如何上传第三方jar包至Maven私服让maven项目可以使用第三方jar包
  • .NET C# 操作Neo4j图数据库
  • .Net Core webapi RestFul 统一接口数据返回格式
  • .Net Core 微服务之Consul(二)-集群搭建
  • .NET Core 中插件式开发实现
  • .NET MVC 验证码
  • .Net多线程Threading相关详解