Spring项目对象的序列化存储和加载

@Component
@Slf4j
public class DataQueryCache {


    private static ConcurrentSkipListMap> sqlQuery = new ConcurrentSkipListMap>();

    // 项目关闭的时候存储本地序列化文件
    @PreDestroy
    public void onDestroy() {
        try {
            // sqlQuery.ser为自定义的名字 , .ser为java序列化文件的后缀,默认生成到项目根目录,也可以自定义路径
            FileOutputStream fileOutputStream = new FileOutputStream("sqlQuery.ser");
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(sqlQuery);
            objectOutputStream.close();
            fileOutputStream.close();
        } catch (Exception e) {
            log.error("保存sqlQuery.ser序列化文件失败", e);
        }
    }

    // 类初始化的时候加载本地序列化文件
    static {
        try {
            FileInputStream fileInputStream = new FileInputStream("sqlQuery.ser");
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            ConcurrentSkipListMap> obj = (ConcurrentSkipListMap>) objectInputStream.readObject();
            if (obj != null) {
                sqlQuery.putAll(obj);
            }
            objectInputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            log.error("没有读取到序列化文件sqlQuery.ser", e);
        }

    }

}

你可能感兴趣的:(spring,java,后端)