goswift

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2023 License: MIT Imports: 9 Imported by: 0

README

GoSwift - Embedded cache for golang

High-performance, concurrent embedded caching library for Go applications with support for Hash data type

Features

  • Set & Get command
  • Del command
  • Update command
  • Exists command
  • Support for TTL
  • Support for Disk Save(Snapshots)
  • Support Hash Data type Hset, Hget, HgetAll, HMset
  • Safe Locking

Installation

go mod init github.com/my/repo

Then install goswift:

go get github.com/leoantony72/goswift

Quickstart


package main

import (
    "fmt"
    "github.com/leoantony72/goswift"
)

func main(){
    cache := goswift.NewCache()

    // Value 0 indicates no expiry
    cache.Set("key", "value", 0)

    val, err := cache.Get("key")
    if err !=nil{
        fmt.Println(err)
        return
    }
    fmt.Println("key", val)
}

Disk Save

Snapshot
opt := goswift.CacheOptions{
		EnableSnapshots:  true,
		SnapshotInterval: time.Second*5,
	}
c := goswift.NewCache(opt)

NOTE: If the EnableSnapshot is false, Data saved in the file will not imported

This will take a snapshot of the Data Every 5sec and saves it into a Snapshot.data file. By default Snapshots are disabled and if the SnapshotInterval is not provided default value is 5seconds.

NOTE: Don't delete the Snapshot.data File

Error Handling

const (
	ErrKeyNotFound   = "key does not Exists"
	ErrFieldNotFound = "field does not Exists"
	ErrNotHashvalue  = "not a Hash value/table"
	ErrHmsetDataType = "invalid data type, Expected Struct/Map"
)

These are the common Errors that may occur while writing the code. These Varible provide you a clear and easy Error comparison method to determine errors.

data,err := cache.Get("key")
if err != nil {
	if err.Error() == goswift.ErrKeyNotFound {
        //do something
}
}    

Usage

// Set Value with Expiry
// @Set(key string, val interface{}, exp int)
// Here expiry is set to 1sec
cache.Set("key","value",1000)


// Get Value with key
// @Get(key string) (interface{}, error)
val,err := cache.Get("key")
if err != nil{
    fmt.Println(err)
    return
}


// Update value
// @Update(key string, val interface{}) error
err = cache.Update("key","value2")
if err != nil{
    fmt.Println(err)
    return
}


// Delete command
// @Del(key string)
cache.Del("key")


// Hset command
// @Hset(key, field string, value interface{}, exp int)
// in this case the "key" expires in 1sec
cache.Hset("key","name","value",1000)
cache.Hset("key","age",18,1000)


// HMset command
// @HMset(key string, d interface{}, exp int) error
// Set a Hash by passing a Struct/Map
// ---by passing a struct---
type Person struct{
    Name  string
    Age   int
    Place string
}

person1 := &Person{Name:"bob",Age:18,Place:"NYC"}
err = cache.HMset("key",person1)
if err != nil{
    fmt.Println(err)
    return
}

// ---by passing a map---
person2 := map[string]interface{Name:"john",Age:18,Place:"NYC"}
err = cache.HMset("key",person2)
if err != nil{
    fmt.Println(err)
    return
}


// Hget command
// @HGet(key, field string) (interface{}, error)
// get individual fields in Hash
data,err := cache.HGet("key","field")
if err != nil{
    fmt.Println(err)
    return
}
fmt.Println(data)

// HgetAll command
// @HGetAll(key string) (map[string]interface{}, error)
// gets all the fields with value in a hash key
// retuns a map[string]interface{}
data,err = cache.HGetAll("key")
if err != nil{
    fmt.Println(err)
    return
}


// Exist command
// @Exists(key string) bool
// Check if the key exists
value = cache.Exists("key")
fmt.Println(value)



// AllData command
// @AllData() (map[string]interface{}, int)
// returns all the data in the cache with keys, also with no.of keys present
// returns the value as a map[strirng]interface{}
// !It does not return the expiry time of the key
data,counter := cache.AllData()
fmt.Println(data,counter)

Run the Test

go test ./...

Documentation

Index

Constants

View Source
const (
	ErrKeyNotFound   = "key does not Exists"
	ErrFieldNotFound = "field does not Exists"
	ErrNotHashvalue  = "not a Hash value/table"
	ErrHmsetDataType = "invalid data type, Expected Struct/Map"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

type Cache struct {
	Data map[string]*dataHolder
	// contains filtered or unexported fields
}

func (*Cache) AllData

func (c *Cache) AllData() (map[string]interface{}, int)

returns all data from the map with both key and value, expiry data will not be returned, returned data will be a copy of the original data

func (*Cache) AllDatawithExpiry added in v1.1.0

func (c *Cache) AllDatawithExpiry() map[string]snaphotData

func (*Cache) Del

func (c *Cache) Del(key string)

Delete's the Item from the cache @This must be improved, So that deleted keys does'nt stay in the Heap.

func (*Cache) DeleteExpiredKeys

func (c *Cache) DeleteExpiredKeys()

Deletes the node if it's expired from both Cache(Hash Table) and heap

func (*Cache) Exists

func (c *Cache) Exists(key string) bool

Exists func receives the key check if it exists in the Hash Table and returns a boolean

func (*Cache) ExistsNonBlocking

func (c *Cache) ExistsNonBlocking(key string) bool

Internal exist func wihtout locking(c.mu.Lock)

func (*Cache) Get

func (c *Cache) Get(key string) (interface{}, error)

If exp is not nil, check if the element has expired or not Removes the element from the cache if expired, It does not remove The Node from the Heap, which will handled by the Sweaper. @This must be improved, So that deleted keys does'nt stay in the Heap.

func (*Cache) HGet

func (c *Cache) HGet(key, field string) (interface{}, error)

Retrieves the field value of hash by key and field name

func (*Cache) HGetAll

func (c *Cache) HGetAll(key string) (map[string]interface{}, error)

HgetAll retrives all the fields in a Hash by providing the key

func (*Cache) HMset

func (c *Cache) HMset(key string, d interface{}, exp int) error

HMset takes a Struct/Map as the value , if any other datatype is Provided it will return an error.

func (*Cache) Hset

func (c *Cache) Hset(key, field string, value interface{}, exp int)

Support for Hash data type, Hset func receives key, field and value

func (*Cache) Set

func (c *Cache) Set(key string, val interface{}, exp int)

Adds an element to Hash Set, If exp is provided add the Node to the Heap with Key and expiration time(int64). If exp == 0, Item Never expires, thus it isn't added In the Heap

func (*Cache) Update

func (c *Cache) Update(key string, val interface{}) error

Set a new value for the key only if it already exist. New data will expire at the same time as the prev Key.

type CacheFunction

type CacheFunction interface {
	Exists(key string) bool
	Set(key string, val interface{}, exp int)
	Get(key string) (interface{}, error)
	Del(key string)
	Update(key string, val interface{}) error
	Hset(key, field string, value interface{}, exp int)
	HGet(key, field string) (interface{}, error)
	HGetAll(key string) (map[string]interface{}, error)
	HMset(key string, d interface{}, exp int) error
	AllData() (map[string]interface{}, int)
}

func NewCache

func NewCache(options ...CacheOptions) CacheFunction

Initialize a New CacheFunction type which is an Interfaces for all the availabel function

type CacheOptions added in v1.1.0

type CacheOptions struct {
	EnableSnapshots  bool
	SnapshotInterval time.Duration
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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