e66cc0d858
Otherwise the bridge would continue to run even if the cache is not available.
55 lines
1.3 KiB
Go
55 lines
1.3 KiB
Go
package cache
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
// RedisCache is the redis cache.
|
|
type RedisCache struct {
|
|
client *redis.Client
|
|
duration time.Duration
|
|
}
|
|
|
|
// NewRedisCache creates a new redis cache/client.
|
|
func NewRedisCache(redisURL string, d time.Duration) (Cache, error) {
|
|
c := new(RedisCache)
|
|
ropts, err := redis.ParseURL(redisURL)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
rdb := redis.NewClient(ropts)
|
|
err = rdb.Ping(context.Background()).Err()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
c.client = rdb
|
|
c.duration = d
|
|
return c, nil
|
|
}
|
|
|
|
// Set saves an alert in the cache.
|
|
func (c *RedisCache) Set(fingerprint string, status string) error {
|
|
return c.client.SetEx(context.Background(), fingerprint, status, c.duration).Err()
|
|
}
|
|
|
|
// Contains checks if an alert with a given fingerprint is in the cache
|
|
// and if the status matches.
|
|
func (c *RedisCache) Contains(fingerprint string, status string) (bool, error) {
|
|
val, err := c.client.Get(context.Background(), fingerprint).Result()
|
|
if err == redis.Nil {
|
|
return false, nil
|
|
} else if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
return val == status, nil
|
|
}
|
|
|
|
// Cleanup is an empty function that is simply here to implement the interface.
|
|
// Redis does its own cleanup.
|
|
func (c *RedisCache) Cleanup() {}
|