knife4j3.0.3怎么整合gateway和注册中心

发布时间:2023-05-10 16:31:24 作者:iii
来源:亿速云 阅读:209

这篇文章主要介绍“knife4j3.0.3怎么整合gateway和注册中心”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“knife4j3.0.3怎么整合gateway和注册中心”文章能帮助大家解决问题。

1. 项目依赖管理

<properties>
    <java.version>1.8</java.version>
    <spring-boot.version>2.3.12.RELEASE</spring-boot.version>
    <spring-cloud.version>Hoxton.SR12</spring-cloud.version>
    <spring-cloud-alibaba.version>2.2.10-RC1</spring-cloud-alibaba.version>
    <knife4j.version>3.0.3</knife4j.version>
</properties>

<dependencyManagement>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-dependencies -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>${spring-boot.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-dependencies -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba.cloud/spring-cloud-alibaba-dependencies -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>${spring-cloud-alibaba.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.github.xiaoymin/knife4j-dependencies -->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-dependencies</artifactId>
            <version>${knife4j.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

2. gateway项目

2.1 pom.xml

<!--网关-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!--nacos注册中心-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--swagger美化——knife4j-->
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
</dependency>

2.2 application.yml

server:
  port: 8888

spring:
  main:
    web-application-type: reactive
  application:
    name: gateway

2.3 bootstrap.yml

spring:
  cloud:
    nacos:
      server-addr: localhost:8848
      username: nacos
      password: nacos
      discovery:
        enabled: true
        namespace: 776074db-06ad-4991-bb68-99b41ae971c9
    gateway:
      routes:
        - id: news
          uri: lb://news
          predicates:
            - Path=/news/**
          filters:
            - StripPrefix=1

2.4 获取swagger资源的接口

import lombok.RequiredArgsConstructor;
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.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.List;

/**
 * @author √Angelの爱灬
 * @date 2023/3/23
 */
@RestController
@RequiredArgsConstructor
public class SwaggerController {

    private final SwaggerResourcesProvider swaggerResources;

    @GetMapping("/swagger-resources")
    public Mono<ResponseEntity<List<SwaggerResource>>> swaggerResources() {
        return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK)));
    }
}

2.5 swagger资源配置类

import com.msf.gateway.enums.ServiceEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.route.RouteDefinition;
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 √Angelの爱灬
 * @date 2023/3/23
 */
@Primary
@Component
@RequiredArgsConstructor
public class SwaggerResourceConfig implements SwaggerResourcesProvider {

    private final String API_URI = "v2/api-docs";

    private final GatewayProperties gatewayProperties;

    @Override
    public List<SwaggerResource> get() {
        // 接口资源列表
        List<SwaggerResource> resources = new ArrayList<>();
        // resources为所有路由都加载到文档,如果需要部分显示,在下方使用filter进行过滤即可
        for (RouteDefinition route : gatewayProperties.getRoutes()) {
            route.getPredicates().stream()
                    .filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName()))
                    .forEach(predicateDefinition -> resources.add(swaggerResource(ServiceEnum.getServiceName(route.getId()),
                            predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0").replace("**", API_URI))));
        }
        return resources;
    }

    private SwaggerResource swaggerResource(String name, String url) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(url);
        swaggerResource.setUrl(url);
        swaggerResource.setSwaggerVersion("2.0");
        return swaggerResource;
    }
}

2.6 服务枚举类

import lombok.AllArgsConstructor;

/**
 * 服务列表
 *
 * @author √Angelの爱灬
 * @date 2023/3/23
 */
@AllArgsConstructor
public enum ServiceEnum {
    //新闻模块
    news("新闻模块");

    private final String serviceName;

    public static String getServiceName(String name) {
        for (ServiceEnum service : ServiceEnum.values()) {
            if (name.equals(service.name())) {
                return service.serviceName;
            }
        }
        return "服务路由字典错误!";
    }
}

此后如果新增了其他子服务,在服务枚举类中添加对应的模块即可:枚举name=spring.cloud.gateway.routes.id,serviceName=服务名称

3. 子服务

3.1 pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--nacos服务注册发现-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--swagger美化——knife4j-->
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-micro-spring-boot-starter</artifactId>
    <exclusions>
        <exclusion>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
        </exclusion>
    </exclusions>
</dependency>

3.2 application.yml

server:
  port: 8080

spring:
  application:
    name: news

3.3 bootstrap.yml

spring:
  cloud:
    nacos:
      server-addr: localhost:8848
      username: nacos
      password: nacos
      discovery:
        enabled: true
        namespace: 776074db-06ad-4991-bb68-99b41ae971c9

knife4j:
  enable: true

3.4 swagger配置类

import com.msf.common.constant.Constant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import springfox.documentation.builders.*;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

/**
 * Swagger配置
 *
 * @author √Angelの爱灬
 * @date 2023/3/21
 */
@Slf4j
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Value("${spring.profiles.active:}")
    private String active;

    @Bean
    public Docket docDocket() {
        boolean enableSwagger = !Constant.SPRING_PROFILES_ACTIVE_PRO.equalsIgnoreCase(active);
        return new Docket(DocumentationType.SWAGGER_2)
                // 非生产环境启用
                .enable(enableSwagger)
                .apiInfo(apiInfo())
                .globalResponses(HttpMethod.GET, globalResponse())
                .globalResponses(HttpMethod.POST, globalResponse())
                .globalResponses(HttpMethod.PUT, globalResponse())
                .globalResponses(HttpMethod.DELETE, globalResponse())
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                .globalRequestParameters(globalRequestParameters());
    }

    private ApiInfo apiInfo() {
        String title = "新闻模块";
        String description = "<div style='font-size:14px;color:red;'>新闻模块knife4j接口文档</div>";
        String version = "1.0.0";
        String termsOfServiceUrl = "";
        Contact contact = new Contact("√Angelの爱灬", "", "");
        return new ApiInfoBuilder()
                .title(title)
                .description(description)
                .version(version)
                .termsOfServiceUrl(termsOfServiceUrl)
                .contact(contact)
                .build();
    }

    private List<Response> globalResponse(){
        List<Response> responseList = new ArrayList<>();
        responseList.add(new ResponseBuilder().code("401").description("未认证").build());
        responseList.add(new ResponseBuilder().code("403").description("请求被禁止").build());
        responseList.add(new ResponseBuilder().code("404").description("找不到资源").build());
        return responseList;
    }

    private List<RequestParameter> globalRequestParameters() {
        List<RequestParameter> parameters = new ArrayList<>();
        RequestParameterBuilder requestParameterBuilder = new RequestParameterBuilder();
        RequestParameter username = requestParameterBuilder
                .name("username").description("用户账号").in(ParameterType.HEADER)
                .build();

        RequestParameter token = requestParameterBuilder
                .name("token").description("token").in(ParameterType.HEADER)
                .build();

        parameters.add(username);
        parameters.add(token);
        return parameters;
    }

}

关于“knife4j3.0.3怎么整合gateway和注册中心”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。

推荐阅读:
  1. Spring Security 整合JWT(四)
  2. Ruby-GetText-Package 的使用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

knife4j gateway

上一篇:怎么使用html+css实现页面书本翻页特效

下一篇:Vue中Vue-Baidu-Map基本使用方法是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》