一、项目整合整合swagger
1.1引入pom文件
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
1.2添加配置类
package com.lg.accountservice.config;
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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
private static final String VERSION = "1.0.0";
/**
* 创建API
*/
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//指定接口包所在路径
.apis(RequestHandlerSelectors.basePackage("com.lg.accountservice.controller"))
.paths(PathSelectors.any())
.build();
}
/**
* 添加摘要信息
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("account-service接口文档")
.contact(new Contact("lg","null",""))
.version(VERSION)
.description("account-service接口文档")
.build();
}
}
1.3添加相关注解
swagger常用注解自行百度
示例代码:
package com.lg.accountservice.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lg.accountservice.model.Account;
import com.lg.accountservice.service.AccountService;
import com.lg.common.model.ResultData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
@RestController
@Slf4j
@Api(tags = "账户接口")
public class AccountController {
@Autowired
private AccountService accountService;
@ApiOperation(value = "获取")
@ApiImplicitParam(name = "accountCode",value = "账户编码", required = true,paramType = "path")
@GetMapping("/account/{accountCode}")
public ResultData<Account> getByCode(@PathVariable String accountCode) {
log.info("get account detail,accountCode is :{}", accountCode);
QueryWrapper<Account> objectQueryWrapper = new QueryWrapper<>();
objectQueryWrapper.eq("account_code", accountCode);
Account account = accountService.getOne(objectQueryWrapper);
return ResultData.ok(account);
}
@ApiOperation(value = "更新")
@PostMapping("/account/update")
public ResultData<Boolean> update(Account account) {
log.info("update account:{}", account);
boolean rs = accountService.updateById(account);
if (rs) {
return ResultData.ok();
} else {
return ResultData.fail();
}
}
@ApiOperation(value = "插入")
@PostMapping("/account/insert")
public ResultData<Boolean> insert(Account account) {
log.info("insert account:{}", account);
boolean rs = accountService.save(account);
if (rs) {
return ResultData.ok();
} else {
return ResultData.fail();
}
}
@ApiOperation(value = "删除")
@PostMapping("/account/delete")
@ApiImplicitParam(name = "accountCode" , value = "账户编码",required = true, paramType = "query")
public ResultData<Boolean> delete(@RequestParam String accountCode) {
log.info("delete account,accountCode is {}", accountCode);
QueryWrapper<Account> objectUpdateWrapper = new QueryWrapper<>();
objectUpdateWrapper.eq("account_code", accountCode);
boolean rs = accountService.remove(objectUpdateWrapper);
if (rs) {
return ResultData.ok();
} else {
return ResultData.fail();
}
}
@ApiOperation(value = "扣除余额")
@PostMapping("/account/deduct")
@ApiImplicitParams({
@ApiImplicitParam(name = "accountCode" , value = "账户编码",required = true, paramType = "query"),
@ApiImplicitParam(name = "amount" , value = "金额",required = true, paramType = "query")
})
public ResultData<Boolean> deduct(@RequestParam String accountCode,
@RequestParam BigDecimal amount) {
QueryWrapper<Account> objectQueryWrapper = new QueryWrapper<>();
objectQueryWrapper.eq("account_code", accountCode);
Account account = accountService.getOne(objectQueryWrapper);
if (account == null) {
throw new RuntimeException(accountCode + "账户不存在");
}
BigDecimal subtractAmmount = account.getAmount().subtract(amount);
if (subtractAmmount.compareTo(BigDecimal.ZERO) < 0) {
throw new RuntimeException(accountCode + "账户余额不足");
}
account.setAmount(subtractAmmount);
boolean rs = accountService.updateById(account);
if (rs) {
return ResultData.ok();
} else {
return ResultData.fail();
}
}
}
package com.lg.accountservice.model;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.math.BigDecimal;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
@TableName(value = "account")
@ApiModel(value = "账户model",description = "账户model,用于接口传参")
public class Account {
@ApiModelProperty(value = "主键id")
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@ApiModelProperty(value = "账户编码")
@TableField(value = "account_code")
private String accountCode;
@ApiModelProperty(value = "账户名字")
@TableField(value = "account_name")
private String accountName;
@ApiModelProperty(value = "账户余额")
@TableField(value = "amount")
private BigDecimal amount;
}
1.4访问swagger页面验证
二、gateway网关整合swagger
2.1将各服务模块按照上面步骤进行swagger整合
2.2编写配置类实现 SwaggerResourcesProvider
接口聚合其他微服务的api资源
package com.lg.cloudgateway.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.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import java.util.ArrayList;
import java.util.List;
@Component
@AllArgsConstructor
public class CustomSwaggerResourceProvider implements SwaggerResourcesProvider {
/**
* Swagger2默认的url后缀
*/
public static final String SWAGGER2URL = "/v2/api-docs";
/**
* 网关路由
*/
private final RouteLocator routeLocator;
private final GatewayProperties gatewayProperties;
/**
* 聚合其他服务接口
* @return
*/
@Override
public List<SwaggerResource> get() {
List<SwaggerResource> resourceList = new ArrayList<>();
List<String> routes = new ArrayList<>();
//获取网关中配置的route
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 -> resourceList.add(
swaggerResource(
routeDefinition.getId(),
predicateDefinition
.getArgs()
.get(NameUtils.GENERATED_NAME_PREFIX + "0")
.replace("/**",SWAGGER2URL)
)
)));
return resourceList;
}
private SwaggerResource swaggerResource(String name, String location) {
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setName(name);
swaggerResource.setLocation(location);
swaggerResource.setSwaggerVersion("2.0");
return swaggerResource;
}
}
2.3创建一个聚合接口类
package com.lg.cloudgateway.controller;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import springfox.documentation.swagger.web.*;
import java.util.Optional;
@RestController
@RequestMapping("/swagger-resources")
public class SwaggerHandler {
@Autowired(required = false)
private SecurityConfiguration securityConfiguration;
@Autowired(required = false)
private UiConfiguration uiConfiguration;
private final SwaggerResourcesProvider swaggerResources;
@Autowired
public SwaggerHandler(springfox.documentation.swagger.web.SwaggerResourcesProvider swaggerResources) {
this.swaggerResources = swaggerResources;
}
@GetMapping("/configuration/security")
public Mono<ResponseEntity<SecurityConfiguration>> securityConfiguration() {
return Mono.just(new ResponseEntity<>(
Optional.ofNullable(securityConfiguration).orElse(SecurityConfigurationBuilder.builder().build()), HttpStatus.OK));
}
@GetMapping("/configuration/ui")
public Mono<ResponseEntity<UiConfiguration>> uiConfiguration() {
return Mono.just(new ResponseEntity<>(
Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build()),HttpStatus.OK));
}
@GetMapping("")
public Mono<ResponseEntity> swaggerResources() {
return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK)));
}
}