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; } } } }