spring boot+swagger 生成Restful風格API

這段時間項目告一段落,開始回過頭來補充完善一些資料,包括數據庫設計和API文檔。之前都是手寫文檔,須要手動去調整格式,接口有更新還得改文檔,測試也要單獨寫代碼。html

有了swagger這些工做所有省掉了,只須要在寫接口的時候多加點註解就搞定。java

廢話很少說直接進入主題,先說下步驟:web

一、引入maven依賴spring

二、利用springboot的config配置方式進行配置數據庫

三、在接口上加入swagger註解apache

四、啓動服務進行查看和測試json

一、引入maven依賴

<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.restdocs</groupId>
            <artifactId>spring-restdocs-mockmvc</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-staticdocs</artifactId>
            <version>2.6.1</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.18</version>
        </dependency>

二、利用springboot的config配置方式進行配置

package com.mymall.crawlerTaskCenter.config;

import java.util.ArrayList;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
 
 
@Configuration
@ComponentScan
@EnableSwagger2
public class SwaggerConfig {
 
    @Bean
    public Docket petApi() {
         
        //自定義異常信息
         ArrayList<ResponseMessage> responseMessages = new ArrayList<ResponseMessage>() {{
                add(new ResponseMessageBuilder().code(200).message("成功").build());
                add(new ResponseMessageBuilder().code(400).message("請求參數錯誤").responseModel(new ModelRef("Error")).build());
                add(new ResponseMessageBuilder().code(401).message("權限認證失敗").responseModel(new ModelRef("Error")).build());
                add(new ResponseMessageBuilder().code(403).message("請求資源不可用").responseModel(new ModelRef("Error")).build());
                add(new ResponseMessageBuilder().code(404).message("請求資源不存在").responseModel(new ModelRef("Error")).build());
                add(new ResponseMessageBuilder().code(409).message("請求資源衝突").responseModel(new ModelRef("Error")).build());
                add(new ResponseMessageBuilder().code(415).message("請求格式錯誤").responseModel(new ModelRef("Error")).build());
                add(new ResponseMessageBuilder().code(423).message("請求資源被鎖定").responseModel(new ModelRef("Error")).build());
                add(new ResponseMessageBuilder().code(500).message("服務器內部錯誤").responseModel(new ModelRef("Error")).build());
                add(new ResponseMessageBuilder().code(501).message("請求方法不存在").responseModel(new ModelRef("Error")).build());
                add(new ResponseMessageBuilder().code(503).message("服務暫時不可用").responseModel(new ModelRef("Error")).build());
                add(new ResponseMessageBuilder().code(-1).message("未知異常").responseModel(new ModelRef("Error")).build());
            }};
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.mymall.crawlerTaskCenter.web.rest"))//掃描的API包
                .paths(PathSelectors.any())
                .build()
                .useDefaultResponseMessages(false)
                .globalResponseMessage(RequestMethod.GET, responseMessages)
                .globalResponseMessage(RequestMethod.POST, responseMessages)
                .globalResponseMessage(RequestMethod.PUT, responseMessages)
                .globalResponseMessage(RequestMethod.DELETE, responseMessages);
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("MyMall 爬蟲任務中心Restful APIs")
                .description("author:彭小康  2017年8月28日")
                .version("2.0").build();
    }
 
}

三、在接口上加入swagger註解

package com.mymall.crawlerTaskCenter.web.rest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.mymall.crawlerTaskCenter.domain.CrawlerJob;
import com.mymall.crawlerTaskCenter.log.LogsManager;
import com.mymall.crawlerTaskCenter.service.CrawlerJobService;

@RestController
@RequestMapping(value = "/job")
@Api(value = "爬蟲任務管理", description = "爬蟲任務管理API", tags = "CrawlerJobApi", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public class CrawlerJobController {
	private static org.apache.logging.log4j.Logger logger = LogsManager.getLocalLogger(CrawlerJobController.class.getName(),"job");
	@Autowired
	CrawlerJobService crawlerJobService;
	
	/**
	 * 獲取最新任務
	 * @return
	 */
	@RequestMapping(value = "/getJobs", method = RequestMethod.GET)
	@ApiOperation(value = "getJobs 獲取最新任務", notes = "requires job number")
	public List<CrawlerJob> getJobs(
			@ApiParam(required = false, name = "jobNum", value = "任務數量,若是不傳該參數則默認給20條,若是任務中心少於20條則所有返回") Integer jobNum,
			@ApiParam(required = false, name = "jobType", value = "任務類型:platform-平臺,allNetList-全網列表任務") String jobType,
			@ApiParam(required = false, name = "key", value = "任務key") String key 
			,HttpServletRequest request) {
		String ip = request.getHeader("X-Real-IP");
		if (StringUtils.isBlank(ip) ||"unknown".equalsIgnoreCase(ip)) {
			ip=request.getRemoteAddr();
		}
		logger.info(ip+"領取了"+jobNum+"條任務");
		return crawlerJobService.getJobs(jobNum, jobType,ip,key);
	}
	
	/**
	 * 提交任務
	 * @return
	 */
	@RequestMapping(value = "/submitJob", method = RequestMethod.POST)
	@ApiOperation(value = "submitJob 提交任務", notes = "根據id提交任務")
	public  boolean submitJob(@ApiParam(required = true, name = "job", value = "任務id") String job,HttpServletRequest request) {
		String ip = request.getHeader("X-Real-IP"); request.getParameter("id");
		if (StringUtils.isBlank(ip) ||"unknown".equalsIgnoreCase(ip)) {
			ip=request.getRemoteAddr();
		}
		CrawlerJob cjob=JSON.parseObject(job,CrawlerJob.class);
		logger.info(ip+"提交了任務,id爲:"+cjob.getId());
		return crawlerJobService.submitJob(cjob);
	}
	
	/**
	 * 建立任務
	 * @return
	 */
	@RequestMapping(value = "/createJob", method = RequestMethod.POST)
	@ApiOperation(value = "createJob 建立任務", notes = "根據json建立任務")
	public  boolean createJob(@ApiParam(required = true, name = "taskJsonStr", value = "任務json字符串") String taskJsonStr){
		return crawlerJobService.createJob(taskJsonStr);
	}
	
	/**
	 * 更新任務
	 * @return
	 */
	@RequestMapping(value = "/updateJob", method = RequestMethod.POST)
	@ApiOperation(value = "updateJob 更新任務", notes = "requires job")
	public boolean updateJob(
			@ApiParam(required = false, name = "job", value = "須要更新任務的json格式數據") String job
			,HttpServletRequest request) {
		String ip = request.getHeader("X-Real-IP");
		if (StringUtils.isBlank(ip) ||"unknown".equalsIgnoreCase(ip)) {
			ip=request.getRemoteAddr();
		}
		logger.info(ip+"更新任務:"+job);
		return crawlerJobService.updateJob(job);
	}
}

四、啓動服務進行查看和測試

根據本身服務時間發佈的地址進行訪問,個人地址是:http://localhost:8082/swagger-ui.htmlapi

展開某個接口,提供了測試方法,填寫對應參數,點擊try it按鈕便可看到運行結果springboot

相關文章
相關標籤/搜索