storage

package
v0.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 28, 2020 License: MIT Imports: 7 Imported by: 0

README

storage 模块文档

设计思想

storage 模块对嵌入式键值数据库 BlotDB 提供的 API 进行了封装,为上层提供了统一的接口实现,并且可以作为一个独立的模块使用。

BlotDB 使用 B+Tree 组织索引,写入数据时会立即落盘存储,并利用mmap技术将数据文件映射到内存中,默认映射到内存的文件大小为 256MB(这一设置只在 Linux 平台上有效),BlotDB 非常适合写多读少的场景。

BlotDB 使用 Bucket 存放键值对,其概念类似于Namespace,不同 Bucket 间的键值对无法访问。

使用方法
实例化Storage接口

你可以使用默认的配置初始化一个Storage接口:

package main

import (
   "github.com/wingsxdu/tinyurl/storage"
)

func main() {
	s = storage.New(storage.DefaultConfig())
}

或者自定义配置规则:

package main

import (
   "github.com/wingsxdu/tinyurl/storage"
)

func main() {
	s = storage.New(&storage.Config{
		Path:     "./test/storage.db", // 数据文件存储位置
		MmapSize: 1024 * 1024 * 1024,  // 1GB
	})
}

当关闭程序并在下次启动时,storage 模块会自动读取数据文件中的数据。

接口

键值对操作相关的接口:

  • View(bucket, key []byte) ([]byte, error)方法会开启一个只读事务,并查找指定key的值,需要注意的是,如果该key不存在会返回nil,但是如果keyvalue为空会返回""
  • Update(bucket, key, value []byte) error方法会开启一个读写事务,并查找指定key的值,更新或创建一个key
  • Delete(bucket, key []byte) error方法会删除指定的key,这个方法不会对不存在的key特殊处理,而是返回一个 nil error;
  • Index(value []byte) (uint64, error)方法在指定的index`Bucket 中生成一个自增主键,在存储数据后会返回该主键。

Bucket 操作相关的接口:

  • CreateBucket(bucket []byte) error方法会尝试创建新的 Bucket,如果该 Bucket 已经存在会忽略创建;
  • DeleteBucket(bucket []byte) error方法会删除指定的 Bucket,如果该 Bucket 不存在会忽略返回的错误。

Documentation

Index

Constants

View Source
const (
	StartAt = 123456
)

Variables

View Source
var (
	ErrBucketNotFound  = bolt.ErrBucketNotFound
	ErrKeyAlreadyExist = errors.New("the key already exist")
)

Functions

This section is empty.

Types

type Config

type Config struct {
	// Path is the file path to the storage file.
	Path string
	// BatchInterval is the maximum time before flushing the BatchTx.
	// 提交两次批量事务的最大时间差,默认 100ms
	BatchInterval time.Duration
	// BatchLimit is the maximum puts before flushing the BatchTx.
	// 指定每个批量读写事务能包含的最多操作个数,当超过这个阈值后,当前批量读写事务会自动提交
	BatchLimit int
	MmapSize   int
}

func DefaultConfig

func DefaultConfig() *Config

type Storage

type Storage interface {
	// Methods to manage key/value pairs
	// Read-Only transactions
	View(bucket, key []byte) ([]byte, error)
	// Create or update a key
	// If the key already exist it will return
	Create(bucket, key, value []byte) error
	// Create or update a key
	// If the key not exist it will Create the key
	Update(bucket, key, value []byte) error
	// Delete a key from bucket
	Delete(bucket, key []byte) error
	// Generate a index for the url and store it
	Index(value []byte) (uint64, error)

	// Methods to manage a Bucket
	CreateBucket(bucket []byte) error
	DeleteBucket(bucket []byte) error
}

func New

func New(c *Config) Storage

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL