Data-SimpleKV

 view release on metacpan or  search on metacpan

lib/Data/SimpleKV.pm  view on Meta::CPAN

        eval { decode_utf8($_) } || $_
    } keys %{$self->{cache}};
}

=head2 clear()

Clear all data from memory cache.

=cut

sub clear {
    my ($self) = @_;
    $self->{cache} = {};
    $self->{dirty} = 1;
    return 1;
}

# 私有方法:加载数据
sub _load_data {
    my ($self) = @_;
    
    return unless -f $self->{data_file};
    
    eval {
        open my $fh, '<', $self->{data_file} or die "Cannot open data file: $!";
        
        my $data = retrieve_fd($fh);
        $self->{cache} = $data || {};
        
        close $fh;
    };
    
    if ($@) {
        warn "Failed to load data: $@";
        $self->{cache} = {};
    }
}

# 私有方法:带锁保存数据
sub _save_with_lock {
    my ($self) = @_;
    
    eval {
        # 使用 +> 模式:如果文件不存在则创建,如果存在则截断
        open my $fh, '+>', $self->{data_file} or die "Cannot open data file: $!";
        
        # 获取排他锁
        flock($fh, LOCK_EX) or die "Cannot acquire exclusive lock: $!";
        
        # 确保从文件开头写入
        seek($fh, 0, SEEK_SET);
        
        # 存储数据
        store_fd($self->{cache}, $fh) or die "Cannot store data: $!";
        
        # 确保数据写入磁盘
        $fh->flush();
        
        close $fh or die "Cannot close data file: $!";
        
        chmod 0644, $self->{data_file};
        $self->{dirty} = 0;
    };
    
    if ($@) {
        croak "Failed to save data: $@";
    }
    
    return 1;
}

# 析构函数:自动保存未保存的更改
sub DESTROY {
    my ($self) = @_;
    
    if ($self->{dirty}) {
        eval { $self->save() };
        warn "Auto-save failed during destruction: $@" if $@;
    }
}

1;

__END__

=head1 FILE STRUCTURE

The module stores data files in the following locations:

=over 4

=item * Primary location: /var/lib/simplekv/

=item * Fallback location: $HOME/.simplekv/

=item * Emergency fallback: /tmp/.simplekv/

=back

Files created:

=over 4

=item * {db_name}.db - The main data file (Storable binary format)

=back

File permissions are set to 0644 (readable by all, writable by owner).

=head1 MULTI-PROCESS SAFETY

The module uses file locking to ensure safe concurrent access:

=over 4

=item * Exclusive locks for writing during save operations

=item * Lock files prevent concurrent write operations

=back



( run in 0.957 second using v1.01-cache-2.11-cpan-140bd7fdf52 )