lab2: postgres, sessions, redis, persistence, stale read
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/domain"
|
||||
)
|
||||
|
||||
type MessageCache struct {
|
||||
client *redis.Client
|
||||
}
|
||||
|
||||
func NewMessageCache(client *redis.Client) *MessageCache {
|
||||
return &MessageCache{client: client}
|
||||
}
|
||||
|
||||
func (c *MessageCache) Get(ctx context.Context, chatID, cursor string) ([]*domain.Message, bool) {
|
||||
key := fmt.Sprintf("messages:%s:%s", chatID, cursor)
|
||||
raw, err := c.client.Get(ctx, key).Bytes()
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
var msgs []*domain.Message
|
||||
if err := json.Unmarshal(raw, &msgs); err != nil {
|
||||
return nil, false
|
||||
}
|
||||
return msgs, true
|
||||
}
|
||||
|
||||
func (c *MessageCache) Set(ctx context.Context, chatID, cursor string, msgs []*domain.Message) {
|
||||
key := fmt.Sprintf("messages:%s:%s", chatID, cursor)
|
||||
raw, _ := json.Marshal(msgs)
|
||||
_ = c.client.Set(ctx, key, raw, 30*time.Second).Err()
|
||||
}
|
||||
|
||||
func (c *MessageCache) Invalidate(ctx context.Context, chatID string) error {
|
||||
pattern := fmt.Sprintf("messages:%s:*", chatID)
|
||||
keys, err := c.client.Keys(ctx, pattern).Result()
|
||||
if err != nil || len(keys) == 0 {
|
||||
return err
|
||||
}
|
||||
return c.client.Del(ctx, keys...).Err()
|
||||
}
|
||||
Reference in New Issue
Block a user