我正在研究背包问题,并尝试解决对mongo db使用spring-active的问题。想法是,当我收到用户的背包问题输入时,我将任务状态设置为“已提交”,然后将响应返回给用户,并开始并行处理解决方案,以找到此背包问题的解决方案。在此过程中,问题/任务状态将从提交->开始->完成更改。以下代码的问题是它在mongodb中创建了两个记录。一条状态已提交的记录,另一条状态已完成的记录。两者都有差异ID。请查看下面我尝试过的代码。 仅供参考:我是春季反应性材料的初学者
如果我不立即返回确认,那么对我来说一切正常,并且只会创建一条记录。
https://github.com/Manishmbm2010/Knapsack-reactive
我遇到问题的服务代码
public Mono<Knapsack> saveKnapsackProblem(Knapsack knapsack) {
Mono<Knapsack> acknowledgement = knapsackReactiveRepository.save(knapsack);
acknowledgement
.flatMap(this::calculateSolutionForKnapsack)
.subscribeOn(Schedulers.fromExecutor(executor))
.doOnError(error -> error.printStackTrace())
.subscribe();
return acknowledgement;
}
服务代码,效果很好,但不发送确认
public void simpleSave(Knapsack knapsack) {
knapsackReactiveRepository
.save(knapsack)
.single()
.flatMap(this::calculateSolutionForKnapsack)
.subscribeOn(Schedulers.fromExecutor(executor))
.doOnError(error -> error.printStackTrace())
.doOnSuccess(success -> System.out.println("Item processed"))
.subscribe();
}
背包模型
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
@Data
// @JsonView("knapsack")
public class Knapsack {
@Id private String taskId;;
private Problem problem;
private Solution solution;
private TimeStamp timestamps;
private Status status;
public Knapsack() {
this.timestamps = new TimeStamp();
solution = new Solution();
this.status = Status.SUBMITTED;
}
public enum Status {
SUBMITTED,
STARTED,
COMPLETED
}
}
控制器
@RequestMapping(path = "/knapsack", method = RequestMethod.POST)
public Mono<Knapsack> submitKnapsackProblem(@RequestBody Knapsack knapsack) {
return knapsackService.saveKnapsackProblem(knapsack);
}
输入
{
"problem":{
"capacity":10,
"weights":[5,4,3],
"values":[100,50,200]
}
}
预期输出为确认:
{
{
"taskId": "5cf2f4ec05a36459cd6faab7",
"problem": {
"capacity": 10,
"weights": [
5,
4,
3
],
"values": [
100,
50,
200
]
},
"solution": {
"items": null,
"time": 0
},
"timestamps": {
"submitted": 1559426284,
"started": null,
"completed": null
},
"status": "SUBMITTED"
}
背包准备就绪时的FinalOutput,可以由另一个端点检索:
{
"taskId": "5cf2f4ec05a36459cd6faab7",
"problem": {
"capacity": 10,
"weights": [
5,
4,
3
],
"values": [
100,
50,
200
]
},
"solution": {
"items": [
0,
2
],
"time": 1
},
"timestamps": {
"submitted": 1559426284,
"started": 1559426285,
"completed": 1559426285
},
"status": "COMPLETED"
}