将原先通过Spring管理的Playwright实例改为使用自定义的单例模式进行全局管理, 提升资源控制能力与生命周期管理的灵活性。同时在应用关闭时主动释放Playwright资源,避免内存泄漏。- 删除`BrowserConfig`类,不再通过Spring容器管理Playwright实例 - 新增`PlaywrightManager`单例类,统一管理Playwright的创建、获取和销毁- 在`DesktopApplication`中添加对Playwright实例的关闭调用 - 更新`FtbCrawlNetDy`和`FtbCrawlNetMt`服务类中的Playwright实例获取方式
70 lines
1.8 KiB
Java
70 lines
1.8 KiB
Java
package com.fantaibao.config;
|
|
|
|
import com.microsoft.playwright.Playwright;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
|
/**
|
|
* Playwright单例管理类
|
|
* 用于全局管理和提供Playwright实例
|
|
*/
|
|
@Slf4j
|
|
public class PlaywrightManager {
|
|
|
|
private static volatile PlaywrightManager instance;
|
|
private Playwright playwright;
|
|
|
|
private PlaywrightManager() {
|
|
if (instance != null) {
|
|
throw new RuntimeException("请使用getInstance()方法获取实例");
|
|
}
|
|
try {
|
|
this.playwright = Playwright.create();
|
|
} catch (Exception e) {
|
|
log.error("创建Playwright实例失败", e);
|
|
throw new RuntimeException("创建Playwright实例失败", e);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 获取PlaywrightManager单例实例
|
|
* @return PlaywrightManager实例
|
|
*/
|
|
public static PlaywrightManager getInstance() {
|
|
if (instance == null) {
|
|
synchronized (PlaywrightManager.class) {
|
|
if (instance == null) {
|
|
instance = new PlaywrightManager();
|
|
}
|
|
}
|
|
}
|
|
return instance;
|
|
}
|
|
|
|
/**
|
|
* 获取Playwright实例
|
|
* @return Playwright实例
|
|
*/
|
|
public Playwright getPlaywright() {
|
|
if (playwright == null) {
|
|
throw new RuntimeException("Playwright实例未初始化或已被销毁");
|
|
}
|
|
return playwright;
|
|
}
|
|
|
|
/**
|
|
* 关闭Playwright实例并释放资源
|
|
*/
|
|
public void close() {
|
|
if (playwright != null) {
|
|
try {
|
|
playwright.close();
|
|
} catch (Exception e) {
|
|
log.error("关闭Playwright实例时出错", e);
|
|
} finally {
|
|
playwright = null;
|
|
instance = null;
|
|
}
|
|
}
|
|
}
|
|
|
|
} |