Реализовать lab3 на оценку 4: балансировка и отказ API
This commit is contained in:
Vendored
+56
@@ -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()
|
||||
}
|
||||
Reference in New Issue
Block a user