最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Redis內存數(shù)據(jù)庫示例分析

 更新時間:2022年12月19日 12:17:13   作者:上后左愛  
Redis本身的內容比較復雜。如果你上來,你應該研究一個細節(jié)點,比如連接池和數(shù)據(jù)結構。雖然可以直接了解某一點的詳細來源內容,甚至盡快解決一些意外,但是容易淹沒在失眠的細節(jié)中,整體控制不了Redis

redies dict字典

這是 Redis 最底層的結構,比如 1個DB 下面有 16個Dict

1. 使用接口方式, 基礎實現(xiàn)是simple_dict ,sync_dict ,后續(xù)用戶可以根據(jù)自己的需求進行自定義的實現(xiàn)屬于自己的Dict , 在 forEach 方法 支持匿名函數(shù)方式
type Dict interface {
  Get(key string) (val interface {}, exists bool)
  Len()
  // 回復上次 put 放入
  Put(key string, val interface{}) (result int)
  PutIfAbsent(key string, val interface {}) (result int)
  PutIfExists(key string, val interface{}) (result int)
  Remove(key string) (result int)
  ForEach(consumer Consumer) // 傳入是方法, 返回 bool = true j繼續(xù)遍歷 
  Keys() []string
  RandomKeys(limit int) []string
  // 返回多個不重復的鍵
  RandomDistinctKeys(limit int) []string
  Clear()
}
// Consumer is used to traversal dict, if it returns false the traversal will be break
type Consumer func(key string, val interface{}) bool
package dict
// SimpleDict wraps a map, it is not thread safe
type SimpleDict struct {
	m map[string]interface{}
}
// MakeSimple makes a new map
func MakeSimple() *SimpleDict {
	return &SimpleDict{
		m: make(map[string]interface{}),
	}
}
// Get returns the binding value and whether the key is exist
func (dict *SimpleDict) Get(key string) (val interface{}, exists bool) {
	val, ok := dict.m[key]
	return val, ok
}
// Len returns the number of dict
func (dict *SimpleDict) Len() int {
	if dict.m == nil {
		panic("m is nil")
	}
	return len(dict.m)
}
// Put puts key value into dict and returns the number of new inserted key-value
func (dict *SimpleDict) Put(key string, val interface{}) (result int) {
	_, existed := dict.m[key]
	dict.m[key] = val
	if existed {
		return 0
	}
	return 1
}
// PutIfAbsent puts value if the key is not exists and returns the number of updated key-value
func (dict *SimpleDict) PutIfAbsent(key string, val interface{}) (result int) {
	_, existed := dict.m[key]
	if existed {
		return 0
	}
	dict.m[key] = val
	return 1
}
// PutIfExists puts value if the key is exist and returns the number of inserted key-value
func (dict *SimpleDict) PutIfExists(key string, val interface{}) (result int) {
	_, existed := dict.m[key]
	if existed {
		dict.m[key] = val
		return 1
	}
	return 0
}
// Remove removes the key and return the number of deleted key-value
func (dict *SimpleDict) Remove(key string) (result int) {
	_, existed := dict.m[key]
	delete(dict.m, key)
	if existed {
		return 1
	}
	return 0
}
// Keys returns all keys in dict
func (dict *SimpleDict) Keys() []string {
	result := make([]string, len(dict.m))
	i := 0
	for k := range dict.m {
		result[i] = k
	}
	return result
}
// ForEach traversal the dict
func (dict *SimpleDict) ForEach(consumer Consumer) {
	for k, v := range dict.m {
		if !consumer(k, v) {
			break
		}
	}
}
// RandomKeys randomly returns keys of the given number, may contain duplicated key
func (dict *SimpleDict) RandomKeys(limit int) []string {
	result := make([]string, limit)
	for i := 0; i < limit; i++ {
		for k := range dict.m {
			result[i] = k
			break
		}
	}
	return result
}
// RandomDistinctKeys randomly returns keys of the given number, won't contain duplicated key
func (dict *SimpleDict) RandomDistinctKeys(limit int) []string {
	size := limit
	if size > len(dict.m) {
		size = len(dict.m)
	}
	result := make([]string, size)
	i := 0
	for k := range dict.m {
		if i == limit {
			break
		}
		result[i] = k
		i++
	}
	return result
}
// Clear removes all keys in dict
func (dict *SimpleDict) Clear() {
	*dict = *MakeSimple()
}

Redis的DB實現(xiàn)

針對其中 Command 的實現(xiàn), ping, set ,Get 有具體的實現(xiàn)方法, 采用策略模式形式, 不同的方法 有自己的 Executor 執(zhí)行器

// 指令與結構體之間的關系
var cmdTable = make(map[string]*command)
type command struct {
	executor ExecFunc
	arity    int // allow number of args, arity < 0 means len(args) >= -arity
}
// RegisterCommand registers a new command
// arity means allowed number of cmdArgs, arity < 0 means len(args) >= -arity.
// for example: the arity of `get` is 2, `mget` is -2
func RegisterCommand(name string, executor ExecFunc, arity int) {
	name = strings.ToLower(name)
	cmdTable[name] = &command{
		executor: executor,
		arity:    arity,
	}
}
// Package database is a memory database with redis compatible interface
package database
import (
	"go-redis/datastruct/dict"
	"go-redis/interface/database"
	"go-redis/interface/resp"
	"go-redis/resp/reply"
	"strings"
)
// DB stores data and execute user's commands
type DB struct {
	index int
	// key -> DataEntity
	data dict.Dict // 底層的實現(xiàn)可以進行切換
}
// ExecFunc is interface for command executor, redis 的 指令實現(xiàn), 所有的實現(xiàn) 協(xié)程這種形式
// args don't include cmd line
type ExecFunc func(db *DB, args [][]byte) resp.Reply
// CmdLine is alias for [][]byte, represents a command line
type CmdLine = [][]byte
// makeDB create DB instance
func makeDB() *DB {
	db := &DB{
		data: dict.MakeSyncDict(), // 使用的 sync 的 dict
	}
	return db
}
// Exec executes command within one database
func (db *DB) Exec(c resp.Connection, cmdLine [][]byte) resp.Reply {
	cmdName := strings.ToLower(string(cmdLine[0]))
	cmd, ok := cmdTable[cmdName]
	if !ok {
		return reply.MakeErrReply("ERR unknown command '" + cmdName + "'")
	}
	if !validateArity(cmd.arity, cmdLine) {
		return reply.MakeArgNumErrReply(cmdName)
	}
	fun := cmd.executor
	return fun(db, cmdLine[1:])
}
func validateArity(arity int, cmdArgs [][]byte) bool {
	argNum := len(cmdArgs)
	if arity >= 0 {
		return argNum == arity
	}
	return argNum >= -arity
}
/* ---- data Access ----- */
// GetEntity returns DataEntity bind to given key
func (db *DB) GetEntity(key string) (*database.DataEntity, bool) {
	raw, ok := db.data.Get(key)
	if !ok {
		return nil, false
	}
	entity, _ := raw.(*database.DataEntity)
	return entity, true
}
// PutEntity a DataEntity into DB
func (db *DB) PutEntity(key string, entity *database.DataEntity) int {
	return db.data.Put(key, entity)
}
// PutIfExists edit an existing DataEntity
func (db *DB) PutIfExists(key string, entity *database.DataEntity) int {
	return db.data.PutIfExists(key, entity)
}
// PutIfAbsent insert an DataEntity only if the key not exists
func (db *DB) PutIfAbsent(key string, entity *database.DataEntity) int {
	return db.data.PutIfAbsent(key, entity)
}
// Remove the given key from db
func (db *DB) Remove(key string) {
	db.data.Remove(key)
}
// Removes the given keys from db
func (db *DB) Removes(keys ...string) (deleted int) {
	deleted = 0
	for _, key := range keys {
		_, exists := db.data.Get(key)
		if exists {
			db.Remove(key)
			deleted++
		}
	}
	return deleted
}
// Flush clean database
func (db *DB) Flush() {
	db.data.Clear()
}

具體的實現(xiàn)器

// Ping Executor
func Ping(db *DB, args [][]byte) resp.Reply {
    if len(args) == 0 {
        return &reply.PongReply{}
    } else if len(args) == 1 {
        return reply.MakeStatusReply(string(args[0]))
    } else {
        return reply.MakeErrReply("ERR wrong number of arguments for 'ping' command")
    }
}
// 初始化 方法
func init() {
    RegisterCommand("ping", Ping, -1)
}

Redis持久化Aof

AOF 則以協(xié)議文本的方式,將所有對數(shù)據(jù)庫進行過寫入的命令(及其參數(shù))記錄到 AOF 文件,以此達到記錄數(shù)據(jù)庫狀態(tài)的目的.

package aof
import (
	"go-redis/config"
	databaseface "go-redis/interface/database"
	"go-redis/lib/logger"
	"go-redis/lib/utils"
	"go-redis/resp/connection"
	"go-redis/resp/parser"
	"go-redis/resp/reply"
	"io"
	"os"
	"strconv"
)
// CmdLine is alias for [][]byte, represents a command line
type CmdLine = [][]byte
const (
	aofQueueSize = 1 << 16
)
type payload struct {
	cmdLine CmdLine
	dbIndex int
}
// AofHandler receive msgs from channel and write to AOF file
type AofHandler struct {
	db          databaseface.Database
	aofChan     chan *payload
	aofFile     *os.File
	aofFilename string
	currentDB   int
}
// NewAOFHandler creates a new aof.AofHandler
func NewAOFHandler(db databaseface.Database) (*AofHandler, error) {
	handler := &AofHandler{}
	handler.aofFilename = config.Properties.AppendFilename
	handler.db = db
	// init Load Aof to Memory
	handler.LoadAof()
	aofFile, err := os.OpenFile(handler.aofFilename, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0600)
	if err != nil {
		return nil, err
	}
	handler.aofFile = aofFile
	handler.aofChan = make(chan *payload, aofQueueSize)
	go func() {
		handler.handleAof()
	}()
	return handler, nil
}
func (handler *AofHandler) AddAof(dbIndex int, cmdLine CmdLine) {
	if config.Properties.AppendOnly && handler.aofChan != nil {
		handler.aofChan <- &payload{
			cmdLine: cmdLine,
			dbIndex: dbIndex,
		}
	}
}
// LoadAof read aof file 數(shù)據(jù)回放的功能
func (handler *AofHandler) LoadAof() {
	file, err := os.Open(handler.aofFilename)
	if err != nil {
		logger.Warn(err)
		return
	}
	defer func(file *os.File) {
		err := file.Close()
		if err != nil {
		}
	}(file)
	ch := parser.ParseStream(file)
	fakeConn := &connection.Connection{} // only used for save dbIndex
	// LoadAof recover data
	for p := range ch {
		if p.Err != nil {
			if p.Err == io.EOF {
				break
			}
			logger.Error("parse error: " + p.Err.Error())
			continue
		}
		if p.Data == nil {
			logger.Error("empty payload")
			continue
		}
		r, ok := p.Data.(*reply.MultiBulkReply)
		if !ok {
			logger.Error("require multi bulk reply")
			continue
		}
		ret := handler.db.Exec(fakeConn, r.Args)
		if reply.IsErrorReply(ret) {
			logger.Error("exec err", err)
		}
	}
}
// handleAof listen aof channel and write into file aof 異步形式的落盤
func (handler *AofHandler) handleAof() {
	handler.currentDB = 0
	for p := range handler.aofChan {
		if p.dbIndex != handler.currentDB {
			// select db
			data := reply.MakeMultiBulkReply(utils.ToCmdLine("SELECT", strconv.Itoa(p.dbIndex))).ToBytes()
			_, err := handler.aofFile.Write(data)
			if err != nil {
				logger.Warn(err)
				continue // skip this command
			}
			handler.currentDB = p.dbIndex
		}
		data := reply.MakeMultiBulkReply(p.cmdLine).ToBytes()
		_, err := handler.aofFile.Write(data)
		if err != nil {
			logger.Warn(err)
		}
	}
}

到此這篇關于Redis內存數(shù)據(jù)庫示例分析的文章就介紹到這了,更多相關Redis內存數(shù)據(jù)庫內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Java Swing JPanel面板的使用方法

    Java Swing JPanel面板的使用方法

    這篇文章主要介紹了Java Swing JPanel面板的使用方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-12-12
  • 一篇文章讓你三分鐘學會Java枚舉

    一篇文章讓你三分鐘學會Java枚舉

    這篇文章主要給大家介紹了如何通過三分鐘學會Java枚舉的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-12-12
  • SpringBoot使用hutool操作FTP的詳細過程

    SpringBoot使用hutool操作FTP的詳細過程

    在使用SpringBoot結合hutool操作FTP時,遇到防火墻導致上傳文件大小為0kb的問題,通過設置FTP為被動模式解決,本文詳細解析了FTP的主動模式和被動模式的工作原理、安全性及適用場景,幫助理解FTP的連接方式和解決網(wǎng)絡限制問題
    2024-09-09
  • 常用數(shù)字簽名算法RSA與DSA的Java程序內實現(xiàn)示例

    常用數(shù)字簽名算法RSA與DSA的Java程序內實現(xiàn)示例

    這篇文章主要介紹了常用數(shù)字簽名算法RSA與DSA的Java程序內實現(xiàn)示例,一般來說DSA算法用于簽名的效率會比RSA要快,需要的朋友可以參考下
    2016-04-04
  • SpringBoot實現(xiàn)阿里云快遞物流查詢的示例代碼

    SpringBoot實現(xiàn)阿里云快遞物流查詢的示例代碼

    本文將基于springboot實現(xiàn)快遞物流查詢,物流信息的獲取通過阿里云第三方實現(xiàn),具有一定的參考價值,感興趣的可以了解一下
    2021-10-10
  • Swagger3.0 整合spring boot2.7x避免swagger2.0與boot2.7沖突問題

    Swagger3.0 整合spring boot2.7x避免swagger2.0與boot2.7沖突

    這篇文章主要介紹了Swagger3.0 整合spring boot2.7x避免swagger2.0與boot2.7沖突問題,通過注釋掉2.0引入的倆包,直接引入3.0,文中結合實例代碼給大家介紹的非常詳細,需要的朋友參考下吧
    2023-10-10
  • 踩坑Debug啟動失敗,無報錯信息問題

    踩坑Debug啟動失敗,無報錯信息問題

    在進行項目debug時遇到了無法啟動的問題,項目一直處于正在啟動狀態(tài),但未出現(xiàn)任何報錯信息,分析原因可能是存在不合法的斷點位置,即斷點未打在方法內部,解決方法是檢查所有斷點信息,并移除非法斷點,之后項目能夠正常啟動
    2023-02-02
  • spring.mvc.servlet.load-on-startup屬性方法源碼解讀

    spring.mvc.servlet.load-on-startup屬性方法源碼解讀

    這篇文章主要介紹了spring.mvc.servlet.load-on-startup的屬性方法源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-12-12
  • Java中如何實現(xiàn)不可變Map詳解

    Java中如何實現(xiàn)不可變Map詳解

    這篇文章主要給大家介紹了關于Java中如何實現(xiàn)不可變Map的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作工具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2018-12-12
  • Elasticsearch索引庫和文檔的相關操作詳細指南

    Elasticsearch索引庫和文檔的相關操作詳細指南

    這篇文章主要給大家介紹了關于Elasticsearch索引庫和文檔的相關操作的相關資料,Elasticsearch是用Java開發(fā)并且是當前最流行的開源的企業(yè)級搜索引擎,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2023-11-11

最新評論

赞皇县| 耿马| 紫金县| 澎湖县| 五台县| 静宁县| 余江县| 武清区| 玛纳斯县| 静宁县| 和林格尔县| 遂昌县| 黄石市| 遂溪县| 蒙自县| 中西区| 格尔木市| 青州市| 广东省| 攀枝花市| 正镶白旗| 上虞市| 永德县| 黄冈市| 吴川市| 九龙县| 于田县| 莱芜市| 普定县| 云龙县| 西昌市| 新巴尔虎右旗| 南和县| 思南县| 夏邑县| 信丰县| 成武县| 通山县| 天祝| 饶平县| 西畴县|