請(qǐng)一定掌握SpringBoot這四個(gè)高級(jí)開發(fā)技巧
環(huán)境:SpringBoot3.2.5
1. 輸出所有Controller接口信息
有時(shí),為了更便捷地排查問題,我們可能希望在容器啟動(dòng)時(shí)能夠打印出當(dāng)前項(xiàng)目中所有的Controller接口信息。這樣做可以提供一個(gè)清晰的項(xiàng)目接口概覽,從而幫助我們更快速地定位和解決可能出現(xiàn)的問題。
方式1
logging:
level:
web: trace
輸出結(jié)果
圖片
雖然達(dá)到了目的,但是這將所有web分組的日志都進(jìn)行輸出了,日志信息非常多,我們所期望的僅僅是輸出Controller相關(guān)的信息。
方式2
logging:
level:
'[_org.springframework.web.servlet.HandlerMapping.Mappings]': debug
輸出結(jié)果
圖片
通過上面的設(shè)置,此時(shí)日志信息只輸出了Controller接口,其它的都按照默認(rèn)的輸出。
2. 統(tǒng)計(jì)接口調(diào)用耗時(shí)
一般我們?cè)诓唤柚谌焦ぞ叩那闆r下,打印接口耗時(shí)通常會(huì)在接口處理邏輯的開始和結(jié)束位置分別記錄當(dāng)前時(shí)間戳,然后計(jì)算時(shí)間差來獲取耗時(shí),如下示例:
@GetMapping("/time")
public Object time() throws Exception {
Instant startTime = Instant.now() ;
// TODO, 業(yè)務(wù)操作
System.err.printf("接口耗時(shí): %d 毫秒%n", (Duration.between(startTime, Instant.now()).toMillis())) ;
return "take time" ;
}
上面統(tǒng)計(jì)了耗時(shí)情況,但是不夠準(zhǔn)確,為了更準(zhǔn)確地反應(yīng)處整個(gè)請(qǐng)求處理過程的耗時(shí),包括Spring框架根據(jù)請(qǐng)求查找對(duì)應(yīng)的Controller、攔截器執(zhí)行等操作,SpringMVC在這些過程執(zhí)行完成后是發(fā)布了一個(gè)事件,我們可以通過監(jiān)聽該事件來獲取整個(gè)請(qǐng)求生命周期的耗時(shí),如下示例:
@Component
public class TakeTimeCountListener implements ApplicationListener<ServletRequestHandledEvent> {
@Override
public void onApplicationEvent(ServletRequestHandledEvent event) {
Throwable failureCause = event.getFailureCause() ;
if (failureCause != null) {
System.err.printf("錯(cuò)誤原因: %s%n", failureCause.getMessage()) ;
}
System.err.printf("請(qǐng)求客戶端地址:%s, 請(qǐng)求URL: %s, 請(qǐng)求Method: %s, 請(qǐng)求耗時(shí): %d%n",
event.getClientAddress(),
event.getRequestUrl(),
event.getMethod(),
event.getProcessingTimeMillis()) ;
}
}
通過監(jiān)聽ServletRequestHandledEvent事件,可以有效的獲取客戶端地址,請(qǐng)求的URL等完整的信息,其中ProcessingTimeMillis屬性反應(yīng)的就是這個(gè)請(qǐng)求耗時(shí)情況。
圖片
是不是非常的方便及準(zhǔn)確!
3. 動(dòng)態(tài)注冊(cè)靜態(tài)資源
通常情況下,一般都是在配置文件中或者自定義WebMvcConfigurer進(jìn)行靜態(tài)資源的配置及注冊(cè),如下示例:
spring:
web:
resources:
static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
以上是默認(rèn)的路徑,我們可以在這自定義自己的今天資源路徑。如下添加文件系統(tǒng)目錄
spring:
web:
resources:
static-locations: ..., file:///d:/images/
也可以通過編程的方式注冊(cè)靜態(tài)資源
public class WebConfig implements WebMvcConfigurer {
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/**").addResourceLocations("file:///d:\\images\\") ;
}
}
以上方式都是實(shí)現(xiàn)配置或代碼中定義好,這都需要重啟服務(wù),無法做到實(shí)時(shí)生效。要想實(shí)時(shí)生效可以通過如下方式動(dòng)態(tài)注冊(cè)
@RestController
public class RegController {
@Resource
private SimpleUrlHandlerMapping resourceHandlerMapping ;
@Resource
private ApplicationContext context ;
// 如:requestURI=/s/**, path=d:/images/
@GetMapping("")
public Object reg(String requestURI, String path) throws Throwable {
ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler();
handler.setLocations(List.of(new FileSystemResource(path))) ;
handler.setApplicationContext(context) ;
handler.afterPropertiesSet() ;
resourceHandlerMapping.registerHandler(requestURI, handler);
return "register success";
}
}
通過如上方式動(dòng)態(tài)注冊(cè)靜態(tài)資源,你也可以對(duì)相應(yīng)的靜態(tài)資源進(jìn)行刪除。
4. 容器啟動(dòng)完成操作
當(dāng)你希望Spring容器正確初始化加載完成以后,執(zhí)行一些操作,那么你可以監(jiān)聽ContextRefreshedEvent事件。該實(shí)際的觸發(fā)是在refresh方法執(zhí)行的最后階段。
@Component
public class ContextRefreshedListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
System.out.println("上下文刷新完成...") ;
// TODO
}
}
通過監(jiān)聽該事件,你可以在這里實(shí)現(xiàn)你自己的邏輯。