Added redis support

This commit is contained in:
Artyom Belousov 2019-05-16 14:58:24 +03:00
parent 577664c034
commit 98a8040246
4 changed files with 101 additions and 1 deletions

39
caching/client.go Normal file
View file

@ -0,0 +1,39 @@
package caching
import (
"github.com/go-redis/redis"
"time"
)
type CacheClient struct {
storage *redis.Client
Expiration time.Duration
}
var client *CacheClient
func GetClient() *CacheClient {
if client != nil {
return client
}
client = new(CacheClient)
client.Init()
return client
}
func (client *CacheClient) Init() {
client.storage = redis.NewClient(&redis.Options{
Addr: HOST_NAME,
Password: PASSWORD,
DB: 0,
})
client.Expiration = CACHE_EXPIRATION
}
func (client *CacheClient) Set(key string, value string) {
client.storage.Set(key, value, client.Expiration)
}
func (client *CacheClient) Get(key string) (string, error) {
return client.storage.Get(key).Result()
}

9
caching/secrets.go Normal file
View file

@ -0,0 +1,9 @@
package caching
import (
"time"
)
const HOST_NAME = "localhost:6379"
const PASSWORD = ""
const CACHE_EXPIRATION = time.Hour * 24

36
tests/cache_test.go Normal file
View file

@ -0,0 +1,36 @@
package tests
import (
"github.com/flygrounder/mtg-price-vk/caching"
"github.com/stretchr/testify/assert"
"testing"
"time"
)
func TestGetSet(t *testing.T) {
client := getTestClient()
keyName := "test_key"
value := "test_value"
client.Set(keyName, value)
val, err := client.Get(keyName)
assert.Nil(t, err)
assert.Equal(t, value, val)
}
func TestExpiration(t *testing.T) {
client := getTestClient()
client.Expiration = time.Millisecond
keyName := "test_key"
value := "test_value"
client.Set(keyName, value)
time.Sleep(time.Millisecond * 2)
val, err := client.Get(keyName)
assert.Zero(t, val)
assert.NotNil(t, err)
}
func getTestClient() *caching.CacheClient {
client := new(caching.CacheClient)
client.Init()
return client
}

View file

@ -1,7 +1,9 @@
package vk
import (
"encoding/json"
"errors"
"github.com/flygrounder/mtg-price-vk/caching"
"github.com/flygrounder/mtg-price-vk/cardsinfo"
"github.com/gin-gonic/gin"
"net/http"
@ -39,7 +41,7 @@ func handleSearch(c *gin.Context, req *MessageRequest) {
} else if cardName == "" {
Message(req.Object.UserId, "Карта не найдена")
} else {
prices, _ := cardsinfo.GetSCGPrices(cardName)
prices := GetPrices(cardName)
elements := min(CARDSLIMIT, len(prices))
prices = prices[:elements]
priceInfo := cardsinfo.FormatCardPrices(cardName, prices)
@ -47,6 +49,20 @@ func handleSearch(c *gin.Context, req *MessageRequest) {
}
}
func GetPrices(cardName string) []cardsinfo.CardPrice {
client := caching.GetClient()
val, err := client.Get(cardName)
var prices []cardsinfo.CardPrice
if err != nil {
prices, _ = cardsinfo.GetSCGPrices(cardName)
serialized, _ := json.Marshal(prices)
client.Set(cardName, string(serialized))
return prices
}
json.Unmarshal([]byte(val), &prices)
return prices
}
func getCardNameByCommand(command string) (string, error) {
var name string
switch {