2.4 与spring boot集成
2.4.4 添加依赖
<dependency><groupId>org.optaplanner</groupId><artifactId>optaplanner-spring-boot-starter</artifactId>
</dependency>
2.4.8 创建求解器服务
import org.optaplanner.core.api.solver.SolverJob;
import org.optaplanner.core.api.solver.SolverManager;@RestController
@RequestMapping("/timeTable")
public class TimeTableController {// 注入求解器管理器@Autowiredprivate SolverManager<TimeTable, UUID> solverManager;@PostMapping("/solve")public TimeTable solve(@RequestBody TimeTable problem) {UUID problemId = UUID.randomUUID();// 提交问题并开始求解SolverJob<TimeTable, UUID> solverJob = solverManager.solve(problemId, problem);TimeTable solution;try {// 等待求解结束solution = solverJob.getFinalBestSolution();} catch (InterruptedException | ExecutionException e) {throw new IllegalStateException("Solving failed.", e);}return solution;}
}
2.4.9 配置求解终止条件
application.yml
optaplanner:solver:termination:spent-limit: 5s
2.4.10.2.2. 测试求解器
在单元测试中构造问题数据集,并发送到TimeTableController测试求解器。
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;@SpringBootTest(properties = {// 禁用消耗时间的终止条件,使用最佳分数限制终止条件"optaplanner.solver.termination.spent-limit=1h","optaplanner.solver.termination.best-score-limit=0hard/*soft"})
public class TimeTableControllerTest {@Autowiredprivate TimeTableController timeTableController;@Test@Timeout(600_000)public void solve() {TimeTable problem = generateProblem();TimeTable solution = timeTableController.solve(problem);assertFalse(solution.getLessonList().isEmpty());for (Lesson lesson : solution.getLessonList()) {assertNotNull(lesson.getTimeslot());assertNotNull(lesson.getRoom());}assertTrue(solution.getScore().isFeasible());}...
}