spring cloud Zuul聚合Swagger2

Zuul整合Swagger2

  • 结构图:
    spring cloud Zuul聚合Swagger2_第1张图片

先贴代码

1、聚合工程的父工程pom依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.alsb</groupId>
    <artifactId>zuul-swagger2</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <modules>
        <module>gateway</module>
        <module>registry</module>
        <module>user</module>
        <module>region</module>
    </modules>
    <packaging>pom</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
        <java.version>1.8</java.version>
        <mapper.starter.version>2.1.5</mapper.starter.version>
        <springfox-swagger2.version>2.9.2</springfox-swagger2.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <!-- springCloud -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!-- 通用Mapper启动器 -->
            <dependency>
                <groupId>tk.mybatis</groupId>
                <artifactId>mapper-spring-boot-starter</artifactId>
                <version>${mapper.starter.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <!--swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${springfox-swagger2.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>io.swagger</groupId>
                    <artifactId>swagger-annotations</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>io.swagger</groupId>
                    <artifactId>swagger-models</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

<!--        使用swagger-annotations和swagger-models 1.5.21版本-->
<!--        解决swagger报错 java.lang.NumberFormatException: For input string: ""-->
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.5.21</version>
        </dependency>

        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-models</artifactId>
            <version>1.5.21</version>
        </dependency>
<!--        可以使用swagger-ui或者swagger-bootstrap-ui 大同小异-->
 <!--        <dependency>-->
        <!--            <groupId>io.springfox</groupId>-->
        <!--            <artifactId>springfox-swagger-ui</artifactId>-->
        <!--            <version>${springfox-swagger2.version}</version>-->
        <!--        </dependency>-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.2</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

</project>

2、gateway:网关服务

依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>zuul-swagger2</artifactId>
        <groupId>com.alsb</groupId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>gateway</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

启动器:

@SpringBootApplication
@EnableZuulProxy
@EnableDiscoveryClient
public class GatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }
}

yml配置文件

server:
  port: 1100
spring:
  application:
    name: gateway-service

eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:1200/eureka
    registry-fetch-interval-seconds: 5
  instance:
    ip-address: 127.0.0.1
    prefer-ip-addr·ess: true

zuul:
  ignored-services: '*' # 排除zuul的默认隐射机制
  routes:
    user-service: # 这里是路由id,随意写
      path: /user/** # 这里是映射路径
      serviceId: user-service # 指定服务名称
    region-service:
      path: /region/**
      serviceId: region-service

swagger2配置

@Component
@Primary
@EnableSwagger2
public class GatewaySwaggerResourcesProvider implements SwaggerResourcesProvider {

    //	这里使用了两个方式添加服务

    private final RouteLocator routeLocator;

    public GatewaySwaggerResourcesProvider(RouteLocator routeLocator) {
        this.routeLocator = routeLocator;
    }
    
//	注意yml配置文件的 ignored-services,如果不配置,则会出现重复的swagger文档
    
    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> resourceList = new ArrayList<>();
        List<Route> routes = routeLocator.getRoutes();
        routes.forEach(route ->
                // 添加服务
                resourceList.add(swaggerResource(route.getId(), route.getFullPath().replace("**", "v2/api-docs")))
        );
        return resourceList;
    }
    

//    @Autowired
//    private DiscoveryClient discoveryClient;
//
//    @Value("${spring.application.name}")
//    private String applicationName;
//
//    @Override
//    public List get() {
//        List resources = new ArrayList<>();
//        // 排除自身,将其他的服务添加进去
//        discoveryClient.getServices().stream().filter(s -> !s.equals(applicationName)).forEach(name -> {
//            resources.add(swaggerResource(name, "/" + name + "/v2/api-docs"));
//        });
//        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;
    }
}
@Component
@ConditionalOnClass(SpringfoxWebMvcConfiguration.class)
public class WebMvcConfig extends WebMvcConfigurationSupport {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //doc.html是文档的访问路径
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

3、registry:注册中心服务

依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>zuul-swagger2</artifactId>
        <groupId>com.alsb</groupId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>registry</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

启动器

@SpringBootApplication
@EnableEurekaServer
public class RegistryApplication {
    public static void main(String[] args) {
        SpringApplication.run(RegistryApplication.class, args);
    }
}

yml配置文件

server:
  port: 1200
spring:
  application:
    name: registry-service
eureka:
  client:
    fetch-registry: false
    register-with-eureka: false
    service-url:
      defaultZone: http://127.0.0.1:1200/eureka

4、user:用户服务

依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>zuul-swagger2</artifactId>
        <groupId>com.alsb</groupId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>user</artifactId>

    <dependencies>
        <!--web启动器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--eureka客户端-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!-- mysql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- 通用Mapper启动器 -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

启动器

@SpringBootApplication
@EnableDiscoveryClient
@MapperScan("com.alsb.user.mapper")
public class UserApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserApplication.class, args);
    }
}

yml配置文件

server:
  port: 1300
spring:
  application:
    name: user-service
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/demo?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=CTT
    username: root
    password: root
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:1200/eureka/
  instance:
    ip-address: 127.0.0.1
    prefer-ip-addr·ess: true

mybatis:
  type-aliases-package: com.alsb.user.entity
  mapperLocations: classpath*:/mapper/*.xml
  configuration:
    mapUnderscoreToCamelCase: true

swagger2配置

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.alsb.user.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("后台用户管理API")
                .description("用户管理")
                .version("1.0")
                .build();
    }
}
@Configuration
public class SwaggerApiConfig {

    public static final String USER = "User";

    @Autowired
    public SwaggerApiConfig(Docket docket) {
        docket.tags(new Tag(USER, "用户管理"));
    }
}

controlller(只展示控制层)

@RestController
@RequestMapping("/user")
@Api(tags = SwaggerApiConfig.USER)
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    @ApiOperation(value = "根据主键查询用户")
    public ResponseEntity<User> queryByPrimaryKey(@ApiParam(value = "主键 用户id",required = true) @PathVariable Integer id) {
        return ResponseEntity.ok(userService.queryByPrimaryKey(id));
    }

    @PostMapping("/add")
    @ApiOperation(value = "新增用户")
    public ResponseEntity<Void> addUser(@RequestBody User user) {
        userService.addUser(user);
        return ResponseEntity.ok().build();
    }
}

5、region:地区服务(略,类似user服务)

启动后效果图

spring cloud Zuul聚合Swagger2_第2张图片
相关链接:
Zuul的常用注解及配置
Swagger2 异常 NumberFormatException:For input string:""

你可能感兴趣的:(spring cloud Zuul聚合Swagger2)