【发布时间】:2021-03-17 16:20:42
【问题描述】:
第一次使用 Quarkus,这可能是一个菜鸟问题,但我不知道如何解决。 我正在尝试设置一个应该运行遗传算法(由 Jenetics 制作)并返回结果的端点。 这是端点定义:
@Path("/items")
public class ItemResource {
@Inject
ItemService service;
@GET
public List<Item> getItems() {
return service.getItems();
}
}
端点要求执行到下面的服务类:
@ApplicationScoped
public class ItemService {
@Inject
ItemMapper mapper;
@Transactional
public List<Item> getItems() {
int numOfItems = Math.toIntExact(Item.count());
IntegerChromosome chromosome = IntegerChromosome.of(0, numOfItems - 1, 14);
Factory<Genotype<IntegerGene>> factory = Genotype.of(chromosome);
Engine<IntegerGene, Double> engine = Engine
.builder(this::fitnessFunction, factory)
.build();
Genotype<IntegerGene> result = engine.stream()
.limit(100)
.collect(EvolutionResult.toBestGenotype());
return mapper.toItems(result);
}
}
最后这是映射器类:
@ApplicationScoped
public class ItemMapper {
public List<Item> toItems(Genotype<IntegerGene> genotype) {
List<Item> items = Item.listAll();
return genotype.chromosome().stream()
.map(IntegerGene::intValue)
.map(items::get)
.collect(Collectors.toList());
}
}
当我运行上面的代码时,我得到以下异常:
Error handling 0d80baf3-12da-49ec-b8d0-e48472c801c9-1, org.jboss.resteasy.spi.UnhandledException: java.util.concurrent.CancellationException: javax.enterprise.context.ContextNotActiveException
代码在标准 Java 应用程序中完美运行,但不能在 Web 服务中运行。有什么想法吗?
【问题讨论】:
-
将
@Transactional移动到ItemResource是否有效? -
不,它会抛出同样的异常。
-
你能添加堆栈跟踪吗?
Item是否包含数据库访问代码?计算的任何部分(在Item或 Jenetics 中)是否异步 - 即在另一个线程上? -
默认情况下,Jenetics 使用
ForkJoinPool.defaultPool()同时评估适应度值。如果这是问题所在,您可以在构建引擎时显式设置使用的Executor。是的,完整的堆栈跟踪会很有用。 -
有没有办法为 Jenetics 配置特定的线程池?