Перенес основы lab3 в lab4

This commit is contained in:
Daria0w0
2026-11-06 14:44:30 +03:00
parent ec540a1a72
commit 9197e151ba
59 changed files with 4761 additions and 3 deletions
+56
View File
@@ -0,0 +1,56 @@
package cache
import (
"context"
"encoding/json"
"time"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
"github.com/redis/go-redis/v9"
)
const ProfileTTL = 60 * time.Second
type Profiles struct{ client *redis.Client }
func NewProfiles(address string) *Profiles {
return &Profiles{client: redis.NewClient(&redis.Options{
Addr: address,
Protocol: 2,
MaxRetries: -1,
DialTimeout: 200 * time.Millisecond,
ReadTimeout: 200 * time.Millisecond,
WriteTimeout: 200 * time.Millisecond,
PoolTimeout: 200 * time.Millisecond,
ContextTimeoutEnabled: true,
PoolSize: 10,
MaxActiveConns: 10,
MinIdleConns: 0,
})}
}
func (p *Profiles) Close() error { return p.client.Close() }
func (p *Profiles) Get(ctx context.Context, id string) (model.User, bool) {
ctx, cancel := context.WithTimeout(ctx, 250*time.Millisecond)
defer cancel()
raw, err := p.client.Get(ctx, "profile:v1:"+id).Bytes()
if err != nil {
return model.User{}, false
}
var user model.User
if json.Unmarshal(raw, &user) != nil || user.ID != id || user.Username == "" || user.DisplayName == "" || user.CreatedAt.IsZero() {
return model.User{}, false
}
return user, true
}
func (p *Profiles) Set(ctx context.Context, user model.User) {
raw, err := json.Marshal(user)
if err != nil {
return
}
ctx, cancel := context.WithTimeout(ctx, 250*time.Millisecond)
defer cancel()
_ = p.client.Set(ctx, "profile:v1:"+user.ID, raw, ProfileTTL).Err()
}