springboot swagger 健康检查

/**
 * swagger访问页面 http://127.0.0.1:8989/abc/swagger-ui.html
 * swagger的Json信息 http://127.0.0.1:8989/abc/v2/api-docs
 * 
 * 通过curl可以访问这两个restful接口
 * curl -v -F "file=@/d/tools/Merge.exe" cgsl/api/myapp/v1/up
 * curl -v cgsl/api/myapp/v1/desk
 */
@EnableSwagger2
@SpringBootApplication
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class);
    }
}

@RestController
class Desk{
    @ApiOperation(value="更新信息", notes="根据url的id来指定更新用户信息")
    @RequestMapping(value="/desk",method = RequestMethod.GET)
    public String getit() {
        System.out.println("kkkkk");
        return "abc";
    }
    
    @RequestMapping(value="/up", method = RequestMethod.POST)
    public String uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String contentType = file.getContentType();
        String fileName = file.getOriginalFilename();
        System.out.println("fileName-->" + fileName);
        System.out.println("getContentType-->" + contentType);
        String filePath = ("upload/");
        try {
            uploadFile(file.getBytes(), filePath, fileName);
        } catch (Exception e) {
            return "uploadimg failed:" + e.getMessage();
        }
        //返回json
        return "uploadimg success";
    }
    private void uploadFile(byte[] file, String filePath, String fileName) throws Exception { 
        File targetFile = new File(filePath);  
        if(!targetFile.exists()){    
            targetFile.mkdirs();    
        }
        try(FileOutputStream out = new FileOutputStream(filePath+fileName)){
            out.write(file);
        }
    }
}

/**
 * 可以不要这个类,但生成的swagger页面中,有不可识别的resful接口。
 * 在这个类中设置basePackage("com.gaofeng"),避免多余的restful接口。
 */
@Configuration
class Swagger2 {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.gaofeng"))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot利用swagger构建api文档")
                .description("简单优雅的restfun风格,http://blog.csdn.net/forezp")
                .termsOfServiceUrl("http://blog.csdn.net/forezp")
                .version("1.0")
                .build();
    }
}

要使用自定义的swagger.json

package gaofeng.springboot;


@EnableSwagger2
@SpringBootApplication
public class App {
    public static void main( String[] args ){
    	new SpringApplication(App.class).run();
    }
}
@RestController
class Desk{
	// curl http://127.0.0.1:8080/hello?name=99 -d ""
	// curl http://127.0.0.1:8080/hello -d "name=99"
	@RequestMapping(value="/hello",method=RequestMethod.POST)
	public String hello(String name) {
		return "hello,"+name;
	}
	
	// http://localhost:8080/swagger-ui.html
	@RequestMapping(value="/swagger-resources",method=RequestMethod.GET,produces="application/json;charset=UTF-8")
	public String swagger_resources() {
		return ("[{'name':'default','location':'/v2/api-docs','swaggerVersion':'2.0'},"
	           +"{'name':'default2','location':'/api-docs2','swaggerVersion':'2.0'}]")
	           .replace('\'', '"');
	}
	
	@RequestMapping(value="/api-docs2",method=RequestMethod.GET,produces="application/json;charset=UTF-8")
	public String api_docs2() throws IOException {
		byte[] all = Files.readAllBytes(Paths.get("G:\\gaofeng\\k8s\\kubernetes\\api\\swagger-spec\\api.json"));
		return new String(all);
	}		
}
---------------------------------------------------
	
		org.springframework.boot
		spring-boot-starter-parent
		1.5.0.RELEASE
	

	
		UTF-8
		1.8
	

	
		
			org.springframework.boot
			spring-boot-starter-web
		
		
			io.springfox
			springfox-swagger2
			2.6.1
		
		
			io.springfox
			springfox-swagger-ui
			2.6.1
		

	

 

 

要增加健康检查,只需要引入一个jar就可以

		
			org.springframework.boot
			spring-boot-starter-actuator
		

打印日志中可以看到

 Mapped "{[/loggers/{name:.*}],methods=[GET],produces=
 Mapped "{[/loggers/{name:.*}],methods=[POST],consumes
 Mapped "{[/loggers || /loggers.json],methods=[GET],pr
 Mapped "{[/dump || /dump.json],methods=[GET],produces
 Mapped "{[/heapdump || /heapdump.json],methods=[GET],
 Mapped "{[/info || /info.json],methods=[GET],produces
 Mapped "{[/trace || /trace.json],methods=[GET],produc
 Mapped "{[/metrics/{name:.*}],methods=[GET],produces=
 Mapped "{[/metrics || /metrics.json],methods=[GET],pr
 Mapped "{[/health || /health.json],methods=[GET],prod
 Mapped "{[/autoconfig || /autoconfig.json],methods=[G
 Mapped "{[/configprops || /configprops.json],methods=
 Mapped "{[/env/{name:.*}],methods=[GET],produces=[app
 Mapped "{[/env || /env.json],methods=[GET],produces=[
 Mapped "{[/auditevents || /auditevents.json],methods=
 Mapped "{[/mappings || /mappings.json],methods=[GET],

但是访问env等url时,提示没有权限

可以关闭鉴权

application.properties添加配置参数
management.security.enabled=false

或者开启登录功能


  org.springframework.boot
  spring-boot-starter-security

application.properties 添加用户名和密码
security.user.name=admin
security.user.password=123456
management.security.enabled=true
management.security.role=ADMIN

然后访问时,浏览器会提示输入用户名和密码

浏览器发送的请求头中,会增加一条header   

Authorization:

Basic YWRtaW46MTIzNDU2

YWRtaW46MTIzNDU2是base64编码的字符串,利用在线base64解码网站,解码后信息是admin:123456

还有其它比较安全的认证方式,比如Digest认证

Digest认证采用一中NONCE随机字符串,用户的每次认证都需要哈希和MD5(用户名和密码),并加入这个盐值,客户端和服务器端每次的NONCE都是不一样的,这样就保证了认证的安全性和不可重放性。

 

 

 

 

你可能感兴趣的:(java)