每当我尝试缓存在运行时编译Java类的方法的结果时,第一次一切正常,但是第二次(假设是从缓存中获取结果时),它会给我{{1 }}。我不知道这是不可能实现的还是做错了什么。
这是我使用缓存调用方法的方式:
class Controller
{
public function __construct($model, $view)
{
$this->model = $model;
$this->view = $view;
}
public function show()
{
return $this->view->render($this->model->getData());
}
}
$controller = new Controller();
$controller->show();
这是具有可实现方法的类:
ClassNotFoundException
我得到这个异常:
public void execute() throws Exception {
MyClass myclass = new MyClass();
String code = "This is a really long JavaClass that implements CompiledClass"; // Retrieve JavaCode from somewhere
for (int i = 0; i < 10; i++) {
CompiledClass obj = myclass.getInstance("NameClassToCompile", code);
}
}
这是我的Hazelcast配置的方式:
@Component
@CacheConfig(cacheNames = "myCache")
public class MyClass implements SomeClass {
@Override
@Cacheable(key = "#name")
public CompiledClass getInstance(String name, String code) throws CustomException {
try {
// Save source in .java file.
File root = Files.createTempDirectory(null).toFile();
File sourceFile = new File(root, (this.getClass().getPackage().getName() + File.separator + name).replace('.', '/') + ".java");
sourceFile.getParentFile().mkdirs();
Files.write(sourceFile.toPath(), code.getBytes(StandardCharsets.UTF_8));
// Compile source file.
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, sourceFile.getPath());
// Load and instantiate compiled class.
Class<?> cls;
try (URLClassLoader classLoader = URLClassLoader.newInstance(new URL[]{root.toURI().toURL()})) {
cls = Class.forName((this.getClass().getPackage().getName() + "." + name), true, classLoader);
}
return (CompiledClass) cls.getDeclaredConstructor().newInstance();
} catch (InvocationTargetException | NoSuchMethodException | InstantiationException | IllegalAccessException | IOException | ClassNotFoundException e) {
throw new CustomException("didn't work", e);
}
}
这是实现所有已编译类的接口。
com.hazelcast.nio.serialization.HazelcastSerializationException: java.lang.ClassNotFoundException: com.mycompany.myartifact.mypackage.NameClassToCompile
这是在运行时编译的代码示例:
@Bean
public Config hazelCastConfig() {
return new Config()
.setInstanceName("hazelcast")
.addMapConfig(
new MapConfig()
.setName("myCache")
.setMaxSizeConfig(new MaxSizeConfig(200, MaxSizeConfig.MaxSizePolicy.FREE_HEAP_SIZE))
.setEvictionPolicy(EvictionPolicy.LRU)
.setTimeToLiveSeconds(20));
}