• Stars
    star
    2,439
  • Rank 18,861 (Top 0.4 %)
  • Language
    Go
  • License
    MIT License
  • Created almost 10 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

An in-memory cache library for golang. It supports multiple eviction policies: LRU, LFU, ARC

GCache

Test GoDoc

Cache library for golang. It supports expirable Cache, LFU, LRU and ARC.

Features

  • Supports expirable Cache, LFU, LRU and ARC.

  • Goroutine safe.

  • Supports event handlers which evict, purge, and add entry. (Optional)

  • Automatically load cache if it doesn't exists. (Optional)

Install

$ go get github.com/bluele/gcache

Example

Manually set a key-value pair.

package main

import (
  "github.com/bluele/gcache"
  "fmt"
)

func main() {
  gc := gcache.New(20).
    LRU().
    Build()
  gc.Set("key", "ok")
  value, err := gc.Get("key")
  if err != nil {
    panic(err)
  }
  fmt.Println("Get:", value)
}
Get: ok

Manually set a key-value pair, with an expiration time.

package main

import (
  "github.com/bluele/gcache"
  "fmt"
  "time"
)

func main() {
  gc := gcache.New(20).
    LRU().
    Build()
  gc.SetWithExpire("key", "ok", time.Second*10)
  value, _ := gc.Get("key")
  fmt.Println("Get:", value)

  // Wait for value to expire
  time.Sleep(time.Second*10)

  value, err := gc.Get("key")
  if err != nil {
    panic(err)
  }
  fmt.Println("Get:", value)
}
Get: ok
// 10 seconds later, new attempt:
panic: ErrKeyNotFound

Automatically load value

package main

import (
  "github.com/bluele/gcache"
  "fmt"
)

func main() {
  gc := gcache.New(20).
    LRU().
    LoaderFunc(func(key interface{}) (interface{}, error) {
      return "ok", nil
    }).
    Build()
  value, err := gc.Get("key")
  if err != nil {
    panic(err)
  }
  fmt.Println("Get:", value)
}
Get: ok

Automatically load value with expiration

package main

import (
  "fmt"
  "time"

  "github.com/bluele/gcache"
)

func main() {
  var evictCounter, loaderCounter, purgeCounter int
  gc := gcache.New(20).
    LRU().
    LoaderExpireFunc(func(key interface{}) (interface{}, *time.Duration, error) {
      loaderCounter++
      expire := 1 * time.Second
      return "ok", &expire, nil
    }).
    EvictedFunc(func(key, value interface{}) {
      evictCounter++
      fmt.Println("evicted key:", key)
    }).
    PurgeVisitorFunc(func(key, value interface{}) {
      purgeCounter++
      fmt.Println("purged key:", key)
    }).
    Build()
  value, err := gc.Get("key")
  if err != nil {
    panic(err)
  }
  fmt.Println("Get:", value)
  time.Sleep(1 * time.Second)
  value, err = gc.Get("key")
  if err != nil {
    panic(err)
  }
  fmt.Println("Get:", value)
  gc.Purge()
  if loaderCounter != evictCounter+purgeCounter {
    panic("bad")
  }
}
Get: ok
evicted key: key
Get: ok
purged key: key

Cache Algorithm

  • Least-Frequently Used (LFU)

Discards the least frequently used items first.

func main() {
  // size: 10
  gc := gcache.New(10).
    LFU().
    Build()
  gc.Set("key", "value")
}
  • Least Recently Used (LRU)

Discards the least recently used items first.

func main() {
  // size: 10
  gc := gcache.New(10).
    LRU().
    Build()
  gc.Set("key", "value")
}
  • Adaptive Replacement Cache (ARC)

Constantly balances between LRU and LFU, to improve the combined result.

detail: http://en.wikipedia.org/wiki/Adaptive_replacement_cache

func main() {
  // size: 10
  gc := gcache.New(10).
    ARC().
    Build()
  gc.Set("key", "value")
}
  • SimpleCache (Default)

SimpleCache has no clear priority for evict cache. It depends on key-value map order.

func main() {
  // size: 10
  gc := gcache.New(10).Build()
  gc.Set("key", "value")
  v, err := gc.Get("key")
  if err != nil {
    panic(err)
  }
}

Loading Cache

If specified LoaderFunc, values are automatically loaded by the cache, and are stored in the cache until either evicted or manually invalidated.

func main() {
  gc := gcache.New(10).
    LRU().
    LoaderFunc(func(key interface{}) (interface{}, error) {
      return "value", nil
    }).
    Build()
  v, _ := gc.Get("key")
  // output: "value"
  fmt.Println(v)
}

GCache coordinates cache fills such that only one load in one process of an entire replicated set of processes populates the cache, then multiplexes the loaded value to all callers.

Expirable cache

func main() {
  // LRU cache, size: 10, expiration: after a hour
  gc := gcache.New(10).
    LRU().
    Expiration(time.Hour).
    Build()
}

Event handlers

Evicted handler

Event handler for evict the entry.

func main() {
  gc := gcache.New(2).
    EvictedFunc(func(key, value interface{}) {
      fmt.Println("evicted key:", key)
    }).
    Build()
  for i := 0; i < 3; i++ {
    gc.Set(i, i*i)
  }
}
evicted key: 0

Added handler

Event handler for add the entry.

func main() {
  gc := gcache.New(2).
    AddedFunc(func(key, value interface{}) {
      fmt.Println("added key:", key)
    }).
    Build()
  for i := 0; i < 3; i++ {
    gc.Set(i, i*i)
  }
}
added key: 0
added key: 1
added key: 2

Author

Jun Kimura

More Repositories

1

factory-go

A library for setting up Golang objects inspired by factory_bot.
Go
356
star
2

slack

Golang client for the Slack API. **NOTE: This project is already archived, so we recommend that you use https://github.com/slack-go/slack instead.**
Go
185
star
3

gforms

A flexible forms validation and rendering library for golang web development.Inspired by django-forms and wtforms.
Go
124
star
4

mecab-golang

A golang wrapper for mecab.
Go
36
star
5

redis-semaphore

A distributed semaphore and mutex built on Redis.
Python
35
star
6

react-go

Go wrapper around the React and JSX.
Go
31
star
7

adblock

Golang parser for Adblock Plus filters
Go
19
star
8

Flask-request-params

Flask-request-params provides Rails-like interface to HTTP Request Parameters for Flask.
Python
10
star
9

go-flow

go-flow is a Golang library that helps you to create a complex flow of batch jobs.
Go
6
star
10

zapslack

Slack Hook for zap
Go
6
star
11

gsignal

Golang library for monitoring asynchronously signals.
Go
4
star
12

gosem

gosem provides multiple semaphore functions. Currently supports inmemory, redis implementation.
Go
4
star
13

go-v7

Go binding to javascript engine v7.
C
4
star
14

Flask-jsonrpc-over-websocket-example

Example flask code to implement jsonrpc over websocket.
Python
3
star
15

randutil

Random variable utility library for golang. Inspired by python random module.
Go
3
star
16

psort

Partial sorting for golang
Go
2
star
17

logrus_slack

Slack Hooks for Logrus
Go
2
star
18

Gistpy

Command line client for gist.
Python
2
star
19

go-subprocess

[WIP] A convenience wrapper around the `os/exec` module.
Go
2
star
20

cetd

Content Extraction via Text Density (CETD) program provides algorithms to detect and remove the additional content
C++
2
star
21

Twister

Twitter Streaming Server.
Python
1
star
22

vermouth

Go
1
star
23

dynamodb

Golang dynamodb library.
Go
1
star
24

gcoding

An encoding library for golang.
Go
1
star
25

greq

Yet another HTTP client library for golang.
Go
1
star
26

rkvs

simple raft-based kvs
Go
1
star
27

Dym

Show the candidate string such as "Did you mean this?" on git.
Python
1
star
28

gen-validator

Go
1
star
29

DM

Data mining library.
C++
1
star
30

golang-swig-example

swig example codes for golang.
C++
1
star
31

pystol

Python
1
star
32

gocache

[Deprecated] Cache module for golang. See https://github.com/bluele/gcache
Go
1
star
33

FileTransaction

File transaction for python2.x
Python
1
star
34

go-semaphore

Implements basic semaphore and time limited semaphore on go language.
Go
1
star
35

ExtractWord

Python
1
star
36

fsobserve

Yet another file system observer. Supports Linux, OSX, Windows, and etc.
Go
1
star
37

ngram

Rust
1
star
38

interchain-simple-packet

Go
1
star
39

Lamia

Cache Module for Python2.x
Python
1
star
40

forge-tx-replay

A small library for Forge that makes it easy to replay transactions and inspect the contract code and state
Solidity
1
star
41

interchain-packet-router

A very experimental project to define a packet router on interchain
Go
1
star
42

StringMatching

Approximate string matching
1
star
43

PyCliper

Python Tkinter-GUI Application
Python
1
star