数据库

 首页 > 数据库 > MongoDB > MongoDB数据库GridFS Wrapper

MongoDB数据库GridFS Wrapper

分享到:
【字体:
导读:
         摘要:简单写了一个Perl版本的GriFS的wrapper:packageCZone::GridFS;usestrict;useMongoDB::GridFS;usePath::Class;useDigest::fileqw(digest_file_hex);useDigest::MD5qw(md5_hex);useIO::...

MongoDB数据库GridFS Wrapper

简单写了一个Perl版本的GriFS的wrapper:

package CZone::GridFS;
use strict;
use MongoDB::GridFS;
use Path::Class;
use Digest::file qw(digest_file_hex);
use Digest::MD5 qw(md5_hex);
use IO::File;
use Data::Dumper;
use Any::Moose;

has database => (
isa => ‘MongoDB::Database’,
is => ‘ro’,
required => 1
);

has _gridfs => (
isa => ‘MongoDB::GridFS’,
is => ‘ro’,
lazy => 1,
builder => ‘_build__gridfs’,
);

has _file_collection => (
isa => ‘MongoDB::Collection’,
is => ‘ro’,
lazy => 1,
builder => ‘_build__file_collection’
);

sub _build__gridfs {
my $self = shift;
return $self->database->get_gridfs;
}

sub _build__file_collection {
my $self = shift;
return $self->database->get_collection(‘fs.files’);
}

sub get_bytes {
my ($self, $id ) = @_;
my $file = $self->_gridfs->find_one({_id => $id });
my $bytes;
my $fh = new IO::File $bytes,’>';
$file->print($fh);
return $bytes;
}

sub store_file {
my ($self, $file_path) = @_;
my $file = file($file_path)->absolute;
return undef unless -e $file;
my $md5 = digest_file_hex($file,’MD5′);
my $fh = $file->open(‘r’) or return undef;
return $self->_store_fh($fh,$md5);
}

sub _store_fh {
my ($self,$fh,$md5) = @_;
# $grid_file isa MongoDB::GridFS::File
my $grid_file = $self->_gridfs->find_one({ ‘md5′ => $md5});
if ($grid_file) {
$self->_inc_refs($grid_file->info->{_id});
return $grid_file->info->{_id};
}
else {
my $oid = $self->_gridfs->insert($fh,{
refs => 1,
md5 => $md5,
});
return $oid;
}
}

sub store_bytes {
my ($self, $bytes) = @_;
my $md5 = md5_hex($bytes);
my $fh = new IO::File $bytes,’ # my $fh = FileHandle->new;
# $fh->open($bytes,’ return $self->_store_fh($fh,$md5);
}

sub unlink {
my ($self, $id ) = @_;
$self->_dec_refs(MongoDB::OID->new(value =>”$id”));
}

sub _inc_refs {
my ($self,$id) = @_;
$self->_file_collection->update({_id => $id },{ ‘$inc’ => { refs => 1}});

}

sub _dec_refs {
my ($self,$id) = @_;
$self->_file_collection->update({_id => $id },{ ‘$inc’ => { refs => -1}});
}

sub gc {
my $self = shift;
$self->_gridfs->remove({refs => 0});
}

no Any::Moose;
__PACKAGE__->meta->make_immutable;
1;

__END__

这是从czone项目中的PHP代码移植过来的。
方便将gridfs中的文件读写到scalar中。同时,通过检查存储文件的md5值,并记录相同文件的引用计数,相同文件只存储一个copy,节省空间。(BSON格式对于空间的需求是非常大的)

MongoDB数据库GridFS Wrapper
分享到:
MongoDB VS MySQL架构设计的区别
MongoDB VS MySQL架构设计的区别 MySql一直是性价比最高的关系型数据库典范 MongoDB带来了关系数据库以外的NoSql体验。   让我们看一个简单的例子,我们将如何为MySQL(或任何关系数据库)和MongoDB中创建一个数据结构。 MySql设计 我们假设设计个表: People 人物信息表  包含ID 和名字字段 passport...
MySQL和MongoDB LBS快速实现方案
MySQL和MongoDB LBS快速实现方案 今天分享两种,利用GeoHash封装成内置数据库函数的简易方案; A:Mysql 内置函数方案,适合于已有业务,新增加LBS功能,增加经纬度字段方可,避免数据迁移 B:Mongodb 内置函数方案,适合中小型应用,快速实现LBS功能,性能优于A(推荐) =======================================...
  •         php迷,一个php技术的分享社区,专属您自己的技术摘抄本、收藏夹。
  • 在这里……