2 changed files with 50 additions and 0 deletions
@ -1,4 +1,53 @@ |
|||||
package com.yvan.workbench.controller; |
package com.yvan.workbench.controller; |
||||
|
|
||||
|
import org.apache.commons.pool2.impl.GenericObjectPoolConfig; |
||||
|
import org.clever.core.AppShutdownHook; |
||||
|
import org.clever.core.Conv; |
||||
|
import org.clever.js.api.ScriptEngineInstance; |
||||
|
import org.clever.js.api.ScriptObject; |
||||
|
import org.clever.js.api.folder.FileSystemFolder; |
||||
|
import org.clever.js.api.folder.Folder; |
||||
|
import org.clever.js.api.pool.GenericEngineInstancePool; |
||||
|
import org.clever.js.graaljs.pool.GraalSingleEngineFactory; |
||||
|
import org.clever.js.graaljs.utils.InteropScriptToJavaUtils; |
||||
|
import org.clever.web.mvc.annotation.RequestBody; |
||||
|
import org.graalvm.polyglot.Context; |
||||
|
import org.graalvm.polyglot.Value; |
||||
|
|
||||
|
import java.io.File; |
||||
|
import java.time.Duration; |
||||
|
import java.util.Map; |
||||
|
|
||||
public class JsDemo { |
public class JsDemo { |
||||
|
private static final GenericEngineInstancePool<Context, Value> pool; |
||||
|
|
||||
|
static { |
||||
|
String basePath = new File("./yvan-lcc-bench/servo/src/test/resources/javascript").getAbsolutePath(); |
||||
|
Folder rootFolder = FileSystemFolder.createRootPath(basePath); |
||||
|
// 创建对象池配置
|
||||
|
GenericObjectPoolConfig<ScriptEngineInstance<Context, Value>> config = new GenericObjectPoolConfig<>(); |
||||
|
config.setMaxWait(Duration.ofMillis(-1)); |
||||
|
config.setMaxTotal(8); |
||||
|
config.setMinIdle(2); |
||||
|
// 创建对象工厂
|
||||
|
GraalSingleEngineFactory factory = GraalSingleEngineFactory.create(rootFolder); |
||||
|
// 创建对象池
|
||||
|
pool = new GenericEngineInstancePool<>(factory, config); |
||||
|
AppShutdownHook.addShutdownHook(() -> { |
||||
|
factory.close(); |
||||
|
pool.close(); |
||||
|
}); |
||||
|
} |
||||
|
|
||||
|
public static Object runJs(@RequestBody Map<String, Object> params) throws Exception { |
||||
|
String jsCode = Conv.asString(params.get("jsCode")); |
||||
|
ScriptEngineInstance<Context, Value> engineInstance = pool.borrowObject(); |
||||
|
try { |
||||
|
ScriptObject<Value> fun = engineInstance.wrapFunction(jsCode); |
||||
|
Object res = fun.execute(); |
||||
|
return InteropScriptToJavaUtils.INSTANCE.toJavaObject(res); |
||||
|
} finally { |
||||
|
pool.returnObject(engineInstance); |
||||
|
} |
||||
|
} |
||||
} |
} |
||||
|
|||||
Loading…
Reference in new issue