mirror of https://github.com/shadowfacts/ekt.git
Use a thread local script engine
This commit is contained in:
parent
dc40cc2647
commit
7df6669bd0
|
@ -2,8 +2,10 @@ package net.shadowfacts.ekt
|
|||
|
||||
import java.io.File
|
||||
import javax.script.ScriptContext
|
||||
import javax.script.ScriptEngine
|
||||
import javax.script.ScriptEngineManager
|
||||
import javax.script.SimpleScriptContext
|
||||
import kotlin.concurrent.getOrSet
|
||||
|
||||
/**
|
||||
* @author shadowfacts
|
||||
|
@ -42,9 +44,7 @@ fun include(include: String, init: net.shadowfacts.ekt.EKT.DataProvider.() -> Un
|
|||
_result.toString()
|
||||
"""
|
||||
|
||||
private val engine by lazy {
|
||||
ScriptEngineManager().getEngineByExtension("kts")
|
||||
}
|
||||
private val engine = ThreadLocal<ScriptEngine>()
|
||||
|
||||
fun render(env: TemplateEnvironment, template: String = env.template): String {
|
||||
if (env.cacheDir != null && env.cacheFile.exists()) {
|
||||
|
@ -122,6 +122,7 @@ _result.toString()
|
|||
}
|
||||
|
||||
internal fun eval(script: String, env: TemplateEnvironment): String {
|
||||
val engine = engine.getOrSet { ScriptEngineManager().getEngineByExtension("kts") }
|
||||
engine.context = SimpleScriptContext()
|
||||
val bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE)
|
||||
bindings.putAll(env.data)
|
||||
|
|
|
@ -1,17 +1,22 @@
|
|||
package net.shadowfacts.ekt
|
||||
|
||||
import java.io.File
|
||||
import kotlin.concurrent.thread
|
||||
|
||||
/**
|
||||
* @author shadowfacts
|
||||
*/
|
||||
fun main(args: Array<String>) {
|
||||
val res = EKT.renderClasspath("template", "/templates", cacheDir = File("cache")) {
|
||||
for (i in 0..2) {
|
||||
thread {
|
||||
println("Calling from: $i")
|
||||
render()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun render(): String {
|
||||
return EKT.renderClasspath("template", "/templates") {
|
||||
"list" to (listOf(1, 2, 3) asType "List<Int>")
|
||||
}
|
||||
|
||||
File("result.txt").apply {
|
||||
if (!exists()) createNewFile()
|
||||
writeText(res)
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue