Commit 42060fe1 authored by youxiaoji's avatar youxiaoji

* [playwright 初始化通过配置文件初始化,manager默认使用Bean]

parent 1ff00b03
package pangea.hiagent.common.config;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Playwright;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Slf4j
@Configuration
public class PlaywrightConfig {
@Bean
public Playwright playwright() {
log.info("playwright init success");
return Playwright.create();
}
@Bean
public Browser browser(Playwright playwright) {
Browser browser = null;
browser = playwright.chromium().launch(new BrowserType.LaunchOptions()
.setHeadless(true)
.setArgs(java.util.Arrays.asList(
"--no-sandbox",
"--disable-dev-shm-usage",
"--disable-gpu",
"--remote-allow-origins=*")));
browser.onDisconnected((tmp) -> {
log.info("浏览器实例已断开连接");
// 发送监听事件
tmp.close();
});
return browser;
}
}
...@@ -15,14 +15,18 @@ public interface PlaywrightManager { ...@@ -15,14 +15,18 @@ public interface PlaywrightManager {
* *
* @return Playwright实例 * @return Playwright实例
*/ */
Playwright getPlaywright(); default Playwright getPlaywright(){
return null;
}
/** /**
* 获取共享的浏览器实例 * 获取共享的浏览器实例
* *
* @return Browser实例 * @return Browser实例
*/ */
Browser getBrowser(); default Browser getBrowser(){
return null;
}
/** /**
* 为指定用户获取专用的浏览器上下文 * 为指定用户获取专用的浏览器上下文
......
...@@ -2,6 +2,7 @@ package pangea.hiagent.tool.playwright; ...@@ -2,6 +2,7 @@ package pangea.hiagent.tool.playwright;
import com.microsoft.playwright.*; import com.microsoft.playwright.*;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import jakarta.annotation.PreDestroy; import jakarta.annotation.PreDestroy;
...@@ -17,10 +18,11 @@ import java.util.concurrent.*; ...@@ -17,10 +18,11 @@ import java.util.concurrent.*;
public class PlaywrightManagerImpl implements PlaywrightManager { public class PlaywrightManagerImpl implements PlaywrightManager {
// 共享的Playwright实例 // 共享的Playwright实例
private volatile Playwright playwright; @Autowired
private Playwright playwright;
@Autowired
// 共享的浏览器实例 // 共享的浏览器实例
private volatile Browser browser; private Browser browser;
// 用户浏览器上下文映射表(用户ID -> BrowserContext) // 用户浏览器上下文映射表(用户ID -> BrowserContext)
private final ConcurrentMap<String, BrowserContext> userContexts = new ConcurrentHashMap<>(); private final ConcurrentMap<String, BrowserContext> userContexts = new ConcurrentHashMap<>();
...@@ -47,54 +49,54 @@ public class PlaywrightManagerImpl implements PlaywrightManager { ...@@ -47,54 +49,54 @@ public class PlaywrightManagerImpl implements PlaywrightManager {
/** /**
* 延迟初始化Playwright和浏览器实例 * 延迟初始化Playwright和浏览器实例
*/ */
private void lazyInitialize() { // private void lazyInitialize() {
if (!initialized) { // if (!initialized) {
synchronized (initLock) { // synchronized (initLock) {
if (!initialized) { // if (!initialized) {
try { // try {
log.info("正在初始化Playwright管理器..."); // log.info("正在初始化Playwright管理器...");
// Thread.currentThread().setContextClassLoader(Playwright.class.getClassLoader());
// 创建Playwright实例 // // 创建Playwright实例
if (playwright == null) { // if (playwright == null) {
this.playwright = Playwright.create(); // this.playwright = Playwright.create();
} // }
if (browser == null) { // if (browser == null) {
// 启动Chrome浏览器,无头模式 // // 启动Chrome浏览器,无头模式
this.browser = playwright.chromium().launch(new BrowserType.LaunchOptions() // this.browser = playwright.chromium().launch(new BrowserType.LaunchOptions()
.setHeadless(true) // .setHeadless(true)
.setArgs(java.util.Arrays.asList( // .setArgs(java.util.Arrays.asList(
"--no-sandbox", // "--no-sandbox",
"--disable-dev-shm-usage", // "--disable-dev-shm-usage",
"--disable-gpu", // "--disable-gpu",
"--remote-allow-origins=*"))); // "--remote-allow-origins=*")));
//
this.browser.onDisconnected((browser) -> { // this.browser.onDisconnected((browser) -> {
log.info("浏览器实例已断开连接"); // log.info("浏览器实例已断开连接");
this.browser.close(); // this.browser.close();
userContexts.clear(); // userContexts.clear();
this.browser = playwright.chromium().launch(new BrowserType.LaunchOptions() // this.browser = playwright.chromium().launch(new BrowserType.LaunchOptions()
.setHeadless(true) // .setHeadless(true)
.setArgs(java.util.Arrays.asList( // .setArgs(java.util.Arrays.asList(
"--no-sandbox", // "--no-sandbox",
"--disable-dev-shm-usage", // "--disable-dev-shm-usage",
"--disable-gpu", // "--disable-gpu",
"--remote-allow-origins=*"))); // "--remote-allow-origins=*")));
}); // });
} // }
// 每5分钟检查一次超时的用户上下文 // // 每5分钟检查一次超时的用户上下文
cleanupScheduler.scheduleAtFixedRate(this::cleanupExpiredContexts, // cleanupScheduler.scheduleAtFixedRate(this::cleanupExpiredContexts,
5, 3600, TimeUnit.MINUTES); // 5, 3600, TimeUnit.MINUTES);
//
this.initialized = true; // this.initialized = true;
log.info("Playwright管理器初始化成功"); // log.info("Playwright管理器初始化成功");
} catch (Exception e) { // } catch (Exception e) {
log.error("Playwright管理器初始化失败: ", e); // log.error("Playwright管理器初始化失败: ", e);
throw new RuntimeException("Failed to initialize Playwright manager", e); // throw new RuntimeException("Failed to initialize Playwright manager", e);
} // }
} // }
} // }
} // }
} // }
// 移除@PostConstruct注解,避免在Spring初始化时自动调用 // 移除@PostConstruct注解,避免在Spring初始化时自动调用
/* /*
...@@ -104,27 +106,10 @@ public class PlaywrightManagerImpl implements PlaywrightManager { ...@@ -104,27 +106,10 @@ public class PlaywrightManagerImpl implements PlaywrightManager {
* } * }
*/ */
@Override
public Playwright getPlaywright() {
lazyInitialize();
if (playwright == null) {
throw new IllegalStateException("Playwright instance is not initialized");
}
return playwright;
}
@Override
public Browser getBrowser() {
lazyInitialize();
if (browser == null || !browser.isConnected()) {
throw new IllegalStateException("Browser instance is not available");
}
return browser;
}
@Override @Override
public BrowserContext getUserContext(String userId) { public BrowserContext getUserContext(String userId) {
lazyInitialize(); // lazyInitialize();
Browser.NewContextOptions options = new Browser.NewContextOptions() Browser.NewContextOptions options = new Browser.NewContextOptions()
.setViewportSize(1920, 1080) // 设置视口大小为全高清分辨率,适用于Windows 11桌面环境 .setViewportSize(1920, 1080) // 设置视口大小为全高清分辨率,适用于Windows 11桌面环境
.setUserAgent( .setUserAgent(
...@@ -136,7 +121,7 @@ public class PlaywrightManagerImpl implements PlaywrightManager { ...@@ -136,7 +121,7 @@ public class PlaywrightManagerImpl implements PlaywrightManager {
@Override @Override
public BrowserContext getUserContext(String userId, Browser.NewContextOptions options) { public BrowserContext getUserContext(String userId, Browser.NewContextOptions options) {
lazyInitialize(); // lazyInitialize();
if (userId == null || userId.isEmpty()) { if (userId == null || userId.isEmpty()) {
throw new IllegalArgumentException("User ID cannot be null or empty"); throw new IllegalArgumentException("User ID cannot be null or empty");
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment