You need to enable JavaScript to run this app. Spring Boot跨服务器启停的变量状态持久化实现及完整示例咨询
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot跨服务器启停的变量状态持久化实现及完整示例咨询

跨重启状态持久化全链路可运行实现

整体逻辑:将需要跨进程保存的两个运行时状态(当前队列服务位置、上次服务日期)映射为全局单条记录的JPA实体,全程复用Spring Boot自动装配能力,无复杂自定义Bean配置,所有状态直接落库,服务器停止/重启后自动加载上次保存的状态值,和原有代码的业务逻辑100%对齐。

1. 定义存储运行时状态的Entity

这张表全程只存1条全局状态记录,因此固定使用主键值为1,不需要配置自增主键。

import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import java.time.LocalDate;

@Entity
public class AppRuntimeState {
    // 固定主键,全局唯一记录
    @Id
    private Integer id = 1;

    // 对应原代码中需要持久化的两个内存变量
    private Integer nowServing;
    private LocalDate serveDate;

    // JPA要求的无参构造
    public AppRuntimeState() {}

    // 带参构造,用于初始化默认状态
    public AppRuntimeState(Integer nowServing, LocalDate serveDate) {
        this.nowServing = nowServing;
        this.serveDate = serveDate;
    }

    // 全字段getter/setter
    public Integer getId() {return id;}
    public void setId(Integer id) {this.id = id;}
    public Integer getNowServing() {return nowServing;}
    public void setNowServing(Integer nowServing) {this.nowServing = nowServing;}
    public LocalDate getServeDate() {return serveDate;}
    public void setServeDate(LocalDate serveDate) {this.serveDate = serveDate;}
}

2. 创建状态实体的Repository

完全基于Spring Data JPA的自动实现能力,无需手写SQL或额外方法,零配置完成数据库交互。

import org.springframework.data.jpa.repository.JpaRepository;

// 指定实体类型、主键类型,Spring容器会自动生成可注入的实现类
public interface AppRuntimeStateRepository extends JpaRepository<AppRuntimeState, Integer> {
}

3. 实现首次启动的状态初始化

应用第一次启动时,如果数据库中不存在状态记录,自动写入和原代码完全一致的默认值,不需要手动初始化数据。

import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.LocalDate;

@Configuration
public class AppStateInitConfig {
    @Bean
    public ApplicationRunner initDefaultState(AppRuntimeStateRepository stateRepo) {
        return args -> {
            // 若id=1的状态记录不存在,就写入默认初始值
            if (stateRepo.findById(1).isEmpty()) {
                AppRuntimeState defaultState = new AppRuntimeState(
                        0,
                        LocalDate.now().minusDays(1) // 和原代码初始值完全一致
                );
                stateRepo.save(defaultState);
            }
        };
    }
}

4. 改造原Controller的业务逻辑

完全删除原来存在内存中的两个状态变量,所有状态读写都直接操作持久层,保证重启后不会丢失状态。

import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDate;
import java.util.Optional;

@RestController
public class ArticleController {

    // 原有文章操作的Repository保持不变
    @Autowired
    ArticleRepository articleRepo;
    // 注入状态存储的Repository
    @Autowired
    AppRuntimeStateRepository stateRepo;

    /**
     * 改造后的nowServing逻辑
     * @return 当前服务的文章主键ID
     */
    private Integer nowServing() {
        // 每次执行先从数据库读取最新持久化状态
        AppRuntimeState currentState = stateRepo.findById(1).get();
        Integer currentPos = currentState.getNowServing();
        LocalDate lastDate = currentState.getServeDate();

        // 和原逻辑完全一致:判断日期是否变更,需要切换到下一个服务位置
        if (!LocalDate.now().equals(lastDate)) {
            Boolean foundApproved = false;
            Integer nextPos = currentPos + 1;
            // 遍历查找下一个已审核的文章,逻辑和原代码无差异
            while (nextPos < articleRepo.count() && !foundApproved) {
                Optional<Article> article = articleRepo.findById(nextPos);
                if (article.isPresent() && article.get().getApprovalStatus()) {
                    foundApproved = true;
                    break;
                }
                nextPos++;
            }
            // 遍历完队列没有找到已审核文章,回到队列开头
            if (!foundApproved) {
                nextPos = 1;
            }

            // 将新状态写回数据库持久化
            currentState.setNowServing(nextPos);
            currentState.setServeDate(LocalDate.now());
            stateRepo.save(currentState);
            return nextPos;
        }
        // 日期无变化,直接返回数据库中存储的当前位置
        return currentPos;
    }
}

注意事项

  • 所有组件均使用Spring Boot默认自动装配能力,无需手动配置数据源、事务、Bean扫描,新手可直接复制运行
  • 无任何内存存储的业务状态,所有运行时状态全部落库,服务器停止、重启后自动加载上次保存的状态值
  • 业务逻辑和原内存实现完全对齐,没有改动原有规则,仅将内存变量的读写替换为数据库操作
  • 采用单条全局记录的Entity设计,无多余表结构、复杂锁逻辑,适配当前技术积累水平
  • 如果需要零外部依赖快速跑通,可引入H2文件模式的嵌入式数据库,不需要单独安装外部数据库服务

内容的提问来源于stack exchange,提问作者RocketScienceGuy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.03 05:27:00