rkcache

package module
v1.2.17 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2023 License: Apache-2.0 Imports: 12 Imported by: 0

README

rk-cache/redis

Init cache with go-redis/cache or local memory cache from YAML config.

This belongs to rk-boot family. We suggest use this lib from rk-boot.

Supported bootstrap

Bootstrap Description
YAML based Start go-redis/cache from YAML
Code based Start go-redis/cache from code

Installation

  • rk-boot: Bootstrapper base
  • rk-gin: Bootstrapper for gin-gonic/gin Web Framework for API
  • rk-cache/redis: Bootstrapper for go-redis/cache of cache
go get github.com/rookie-ninja/rk-boot/v2
go get github.com/rookie-ninja/rk-gin/v2
go get github.com/rookie-ninja/rk-cache/redis

Quick Start

In the bellow example, we will run Redis locally and implement API of Get/Set of K/V.

  • GET /v1/get, get value
  • POST /v1/set, set value
1.Create boot.yaml

boot.yaml

  • Create web server with Gin framework at port 8080
  • Create Redis entry which connects Redis at localhost:6379 as cache
---
gin:
  - name: cache-service
    port: 8080
    enabled: true
cache:
  - name: redis-cache
    enabled: true
    local:
      enabled: false
    redis:
      enabled: true
2.Create main.go

In the main() function, we implement bellow things.

  • Register APIs into Gin router.
package main

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/rookie-ninja/rk-boot/v2"
	"github.com/rookie-ninja/rk-cache/redis"
	"github.com/rookie-ninja/rk-gin/v2/boot"
	"net/http"
)

var cacheEntry *rkcache.CacheEntry

func main() {
	boot := rkboot.NewBoot()

	boot.Bootstrap(context.TODO())

	// assign cache
	cacheEntry = rkcache.GetCacheEntry("redis-cache")

	// assign router
	ginEntry := rkgin.GetGinEntry("cache-service")
	ginEntry.Router.GET("/v1/get", Get)
	ginEntry.Router.GET("/v1/set", Set)

	boot.WaitForShutdownSig(context.TODO())
}

func Get(ctx *gin.Context) {
	val := ""
	resp := cacheEntry.GetFromCache(&rkcache.CacheReq{
		Key:   "demo-key",
		Value: &val,
	})

	if resp.Error != nil || !resp.Success {
		ctx.JSON(http.StatusInternalServerError, resp.Error)
		return
	}

	ctx.JSON(http.StatusOK, map[string]string{
		"value": val,
	})
}

func Set(ctx *gin.Context) {
	val, ok := ctx.GetQuery("value")
	if !ok {
		ctx.JSON(http.StatusBadRequest, "No value found")
	}

	cacheEntry.AddToCache(&rkcache.CacheReq{
		Key:   "demo-key",
		Value: val,
	})

	ctx.JSON(http.StatusOK, map[string]string{
		"value": val,
	})
}
3.Start server
$ go run main.go

2022-03-09T00:10:50.325+0800    INFO    redis/entry.go:163      Bootstrap CacheRedisEntry       {"entryName": "redis-cache", "localCache": false, "redisCache": true}
2022-03-09T00:10:50.325+0800    INFO    redis@v1.0.1/boot.go:253        Bootstrap redisEntry    {"eventId": "2e47b54a-a46c-4c23-ae51-f105bdbc5836", "entryName": "redis-cache", "entryType": "RedisEntry", "clientType": "Single"}
2022-03-09T00:10:50.325+0800    INFO    redis@v1.0.1/boot.go:261        Ping redis at [localhost:6379]
2022-03-09T00:10:50.330+0800    INFO    redis@v1.0.1/boot.go:267        Ping redis at [localhost:6379] success
2022-03-09T00:10:50.330+0800    INFO    boot/gin_entry.go:624   Bootstrap GinEntry      {"eventId": "2e47b54a-a46c-4c23-ae51-f105bdbc5836", "entryName": "cache-service", "entryType": "GinEntry"}
------------------------------------------------------------------------
endTime=2022-03-09T00:10:50.33088+08:00
startTime=2022-03-09T00:10:50.330832+08:00
elapsedNano=47527
timezone=CST
ids={"eventId":"2e47b54a-a46c-4c23-ae51-f105bdbc5836"}
app={"appName":"","appVersion":"","entryName":"cache-service","entryType":"GinEntry"}
env={"arch":"amd64","az":"*","domain":"*","hostname":"lark.local","localIP":"10.8.0.2","os":"darwin","realm":"*","region":"*"}
payloads={"ginPort":8080}
counters={}
pairs={}
timing={}
remoteAddr=localhost
operation=Bootstrap
resCode=OK
eventStatus=Ended
EOE
4.Validation
4.1 Set value
$ curl "localhost:8080/v1/set?value=my-value"
{"value":"my-value"}
4.2 Get value
$ curl localhost:8080/v1/get
{"value":"my-value"}
4.3 Validate Redis

The key of cache will be encoded with MD5 and value will be base64 encoded.

image

Documentation

Index

Constants

View Source
const CacheRedisEntry = "CacheRedisEntry"

Variables

This section is empty.

Functions

func GetCache

func GetCache(entryName string) *cache.Cache

GetCache get cache.Cache with entryName

func RegisterCacheEntryYAML

func RegisterCacheEntryYAML(raw []byte) map[string]rkentry.Entry

RegisterCacheEntryYAML create entry from config file

Types

type BootCache

type BootCache struct {
	Cache []*BootCacheE `yaml:"cache" json:"cache"`
}

BootCache bootstrap entry from config

type BootCacheE added in v1.1.0

type BootCacheE struct {
	Name        string `yaml:"name" json:"name"`
	Domain      string `yaml:"domain" json:"domain"`
	Description string `yaml:"description" json:"description"`
	Enabled     bool   `yaml:"enabled" json:"enabled"`
	Local       struct {
		Enabled bool `yaml:"enabled" json:"enabled"`
		Size    int  `yaml:"size" json:"size"`
		TtlMin  int  `yaml:"ttlMin" json:"ttlMin"`
	} `yaml:"local" json:"local"`
	Redis       rkredis.BootRedisE `yaml:"redis" json:"redis"`
	LoggerEntry string             `yaml:"loggerEntry" json:"loggerEntry"`
	CertEntry   string             `yaml:"certEntry" json:"certEntry"`
}

type CacheEntry

type CacheEntry struct {
	// contains filtered or unexported fields
}

CacheEntry implementation of rkentry.Entry

func GetCacheEntry

func GetCacheEntry(entryName string) *CacheEntry

func RegisterCacheEntry

func RegisterCacheEntry(opts ...Option) *CacheEntry

RegisterCacheEntry register with Option

func (*CacheEntry) AddToCache

func (entry *CacheEntry) AddToCache(req *CacheReq) *CacheResp

func (*CacheEntry) Bootstrap

func (entry *CacheEntry) Bootstrap(ctx context.Context)

Bootstrap entry

func (*CacheEntry) GetCache

func (entry *CacheEntry) GetCache() *cache.Cache

GetCache returns cache instance

func (*CacheEntry) GetDescription

func (entry *CacheEntry) GetDescription() string

GetDescription returns description of entry

func (*CacheEntry) GetFromCache

func (entry *CacheEntry) GetFromCache(req *CacheReq) *CacheResp

func (*CacheEntry) GetName

func (entry *CacheEntry) GetName() string

GetName returns name of entry

func (*CacheEntry) GetType

func (entry *CacheEntry) GetType() string

GetType returns type of entry

func (*CacheEntry) Interrupt

func (entry *CacheEntry) Interrupt(ctx context.Context)

Interrupt entry

func (*CacheEntry) IsLocalCacheEnabled

func (entry *CacheEntry) IsLocalCacheEnabled() bool

IsLocalCacheEnabled is local cache enabled

func (*CacheEntry) IsRedisCacheEnabled

func (entry *CacheEntry) IsRedisCacheEnabled() bool

IsRedisCacheEnabled is redis cache enabled

func (*CacheEntry) String

func (entry *CacheEntry) String() string

String to string

type CacheReq

type CacheReq struct {
	Key   interface{}
	Value interface{}
}

type CacheResp

type CacheResp struct {
	Success bool
	Error   error
}

type Option

type Option func(e *CacheEntry)

Option entry options

func WithDescription

func WithDescription(description string) Option

WithDescription provide name.

func WithLocalCache

func WithLocalCache(in cache.LocalCache) Option

WithLocalCache provide LocalCache

func WithLoggerEntry

func WithLoggerEntry(entry *rkentry.LoggerEntry) Option

WithLoggerEntry provide rkentry.LoggerEntry entry name

func WithName

func WithName(name string) Option

WithName provide name.

func WithRedisCache

func WithRedisCache(in *rkredis.RedisEntry) Option

WithRedisCache provide RedisEntry

Jump to

Keyboard shortcuts

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