gateway-nacos-knife4j整合加访问权限控制(详细教程适合新手入门)
文章目录子模块配置gateway模块配置最近学习到微服务这块,子模块一个一个的swagger切换调试非常麻烦,于是想聚合在网关,研究了一段时间,发现网上的教程对新手很不友好,所以自己学习了之后整理出来供springboot项目改造成springcloud项目的小伙伴参考,适合新手入门子模块配置需要:1.新增一个config文件2.改动yaml文件3.pom文件新增依赖4.controller跟po
文章目录
最近学习到微服务这块,子模块一个一个的swagger切换调试非常麻烦,于是想聚合在网关,研究了一段时间,发现网上的教程对新手很不友好,所以自己学习了之后整理出来供springboot项目改造成springcloud项目的小伙伴参考,适合新手入门
这是我的版本:
子模块配置
需要:
1.新增一个config文件
2.改动yaml文件
3.pom文件新增依赖
4.controller跟pojo上增加swagger注解(略)
package com.music.netsadcloudums.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.VendorExtension;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
import java.util.ArrayList;
/**
* @author Boss
* ip:port/doc.html
* 账号密码即见配置文件
*/
@Configuration
@EnableSwagger2WebMvc
public class SwaggerConfig {
//配置swagger的Docket的bean实例
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//注意basePackage改成自己每个项目的路径
.apis(RequestHandlerSelectors.basePackage("com.music.netsadcloud"))
.paths(PathSelectors.any())
.build();
}
//配置swagger信息
private ApiInfo apiInfo() {
Contact contact = new Contact("作者姓名", "", "");
return new ApiInfo("XXX接口文档",
"Api Documentation",
"1.0",
"urn:tos",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList<VendorExtension>()
);
}
}
配置文件的作用是增加swagger密码访问的权限
#==============================knife4j配置=======================================
knife4j:
# 开启增强配置
enable: true
basic:
enable: true
# Basic认证用户名
username: test
# Basic认证密码
password: 987789
这里我用的依赖版本是2.0.8,不得不说作者萧明更新版本非常的快,所以高版本的注解有一些跟低版本不一样,不过作用大同小异,具体请去knife4j官网查看
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-micro-spring-boot-starter</artifactId>
<version>${knife4j.version}</version>
</dependency>
gateway模块配置
1.新增两个文件
2.修改yaml文件
3.pom文件新增依赖
新手不用懂为什么需要这两个文件,直接拷贝就行,不用任何修改
新增文件1:
package com.music.netsadcloudgateway.config;
import lombok.AllArgsConstructor;
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;
/**
* @author zhangyang
*/
@Component
@Primary
@AllArgsConstructor
public class SwaggerProvider implements SwaggerResourcesProvider {
public static final String API_URI = "v2/api-docs";
private final RouteLocator routeLocator;
private final GatewayProperties gatewayProperties;
@Override
public 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(routeDefinition -> routeDefinition.getPredicates().stream()
.filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName()))
.forEach(predicateDefinition -> resources.add(swaggerResource(routeDefinition.getId(),
predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0")
.replace("**", API_URI)))));
return resources;
}
private SwaggerResource swaggerResource(String name, String location) {
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setName(name);
swaggerResource.setLocation(location);
swaggerResource.setSwaggerVersion("2.0");
return swaggerResource;
}
}
新增文件2:
package com.music.netsadcloudgateway.handler;
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;
@RestController
public class SwaggerHandler {
@Autowired(required = false)
private SecurityConfiguration securityConfiguration;
@Autowired(required = false)
private UiConfiguration uiConfiguration;
private final SwaggerResourcesProvider swaggerResources;
@Autowired
public SwaggerHandler(SwaggerResourcesProvider swaggerResources) {
this.swaggerResources = swaggerResources;
}
/**
* Swagger安全配置,支持oauth和apiKey设置
*/
@GetMapping("/swagger-resources/configuration/security")
public Mono<ResponseEntity<SecurityConfiguration>> securityConfiguration() {
return Mono.just(new ResponseEntity<>(
Optional.ofNullable(securityConfiguration).orElse(SecurityConfigurationBuilder.builder().build()), HttpStatus.OK));
}
/**
* Swagger UI配置
*/
@GetMapping("/swagger-resources/configuration/ui")
public Mono<ResponseEntity<UiConfiguration>> uiConfiguration() {
return Mono.just(new ResponseEntity<>(
Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build()), HttpStatus.OK));
}
/**
* Swagger资源配置,微服务中这各个服务的api-docs信息
*/
@GetMapping("/swagger-resources")
public Mono<ResponseEntity> swaggerResources() {
return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK)));
}
}
pom文件新增依赖:
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>${knife4j.version}</version>
</dependency>
接下来是重头戏了,gateway的yaml文件配置,这个坑了我很长时间,网上gateway与nacos整合的教学都大同小异互相抄来抄去,对新手一点都不友好
server:
port: 8085
spring:
cloud:
nacos:
discovery:
server-addr: XXX.XXX.26.99:8848
gateway:
discovery:
locator:
enabled: false #让gateway可以发现nacos中的微服务 开启后会自动去掉一层路径,且routes会失效
#如果完全注释routes,knife4j会失效
routes: # 路由数组 指当请求满足什么样的条件的时候,转发到哪个微服务上
# - id: netsadcloud-shop #当前路由标识,要求唯一 (默认值uuid,一般不用,需要自定义)
# uri: lb://netsadcloud-shop #请求最终要被转发的地址 lb指的是从nacos中按照名称获取微服务,并遵循负载均衡策略
# predicates: #断言 判断条件,返回值是boolean 转发请求要返回的条件 (可以写多个)
# - Path=/netsadcloud-shop/** #当请求路径满足path指定的规则时,此路由信息才会正常转发
# filters: #过滤器(在请求传递过程中,对请求做一些手脚)
# - StripPrefix=1 # 在请求转发之前去掉一层路径
- id: netsadcloud-ums
uri: lb://netsadcloud-ums
predicates:
- Path=/netsadcloud-ums/**
filters:
- StripPrefix=1
- id: netsadcloud-music
uri: lb://netsadcloud-music
predicates:
- Path=/netsadcloud-music/**
filters:
- StripPrefix=1
application:
name: netsadcloud-gateway
一开始我从网上粘贴的 enabled 是true,下面别人依旧配置了路由,但是我怎么改filters都不生效,改的我怀疑人生,还以为是springcloud版本问题,网上的一些教程真的很坑爹,坑的我眼泪直流
启动项目: 访问 http://localhost:8085/doc.html 输入账户密码访问
如果你启动了多个子模块,那么左上角可以在子模块之间切换
更多推荐
所有评论(0)