【发布时间】:2021-02-21 21:26:10
【问题描述】:
我想在我的 Spring Boot 服务器启动和停止中保持一个可变状态。例如,一个整数表示服务器在每天递增一次的服务对象队列中的位置(参见下面的“nowServing”):
@RestController
public class ArticleController {
@Autowired
ArticleRepository articleRepo;
// TODO - these two variables need to persist between runnings of the server. Refactor to be set and get from the database.
//the article with id '0' and '1' better be approved!
private Integer nowServing = 0; //where in the queue we are serving an article from at the moment
LocalDate serveDate = LocalDate.now().minusDays(1); //a date associated with the current article being served
/**
* When the date changes, find the next approved article in the queue, and set that as our serving point.
* @return which primary key in our sorted table we're serving
*/
private Integer nowServing() {
if (!LocalDate.now().equals(serveDate)) {
//time to start serving the next article
serveDate = LocalDate.now();
Boolean foundAnApprovedOne = false;
for (nowServing++; ( (nowServing<articleRepo.count()) && (foundAnApprovedOne == false) ); nowServing++) {
Optional<Article> article = articleRepo.findById(nowServing);
if ( (article.isPresent()) && (article.get().getApprovalStatus()) ) {
foundAnApprovedOne = true;
}
}
if (foundAnApprovedOne == false) {
//There are no more approved articles left in the queue. Restart from the beginning
nowServing = 1;
}
}
return nowServing;
}
我搜索了如何保存状态信息,遇到了以下可能的帖子: JPA: Singleton Entity Hibernate/persistence and singleton pattern
我认为每个示例都只是展示整体的一部分,希望观看者知道如何将提供的内容与其他补充组件集成。我现在的 Spring 能力非常有限,我希望研究一个更全面(存储库、实体、控制器等)的简单示例,我可以适应和学习。最好,这个示例将远离 bean 并包含一个实体,以依靠我目前的优势。
【问题讨论】:
-
您可以使用像 Redis 这样的简单内存键值数据库,我认为这会更有效。有一个 Spring Data Redis Spring Boot 启动器,使用起来非常简单。
标签: spring spring-boot