refactor(config): 移除BrowserConfig配置类并引入PlaywrightManager单例管理器

将原先通过Spring管理的Playwright实例改为使用自定义的单例模式进行全局管理,
提升资源控制能力与生命周期管理的灵活性。同时在应用关闭时主动释放Playwright资源,避免内存泄漏。- 删除`BrowserConfig`类,不再通过Spring容器管理Playwright实例
- 新增`PlaywrightManager`单例类,统一管理Playwright的创建、获取和销毁- 在`DesktopApplication`中添加对Playwright实例的关闭调用
- 更新`FtbCrawlNetDy`和`FtbCrawlNetMt`服务类中的Playwright实例获取方式
This commit is contained in:
wangchunxiang
2025-10-15 17:17:17 +08:00
parent 397a2ee83f
commit 7c0c83d39d
5 changed files with 83 additions and 23 deletions

View File

@@ -0,0 +1,70 @@
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;
}
}
}
}