session 패키지 추가
This commit is contained in:
61
session/provider.go
Normal file
61
session/provider.go
Normal file
@ -0,0 +1,61 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/go-redis/redis/v8"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"repositories.action2quare.com/ayo/gocommon"
|
||||
)
|
||||
|
||||
type Provider[T any] struct {
|
||||
redisClient *redis.Client
|
||||
updateChannel string
|
||||
deleteChannel string
|
||||
ttl time.Duration
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func NewProvider[T any](ctx context.Context, redisUrl string, ttl time.Duration) (*Provider[T], error) {
|
||||
redisClient, err := gocommon.NewRedisClient(redisUrl)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Provider[T]{
|
||||
redisClient: redisClient,
|
||||
updateChannel: communication_channel_name_prefix + "_u",
|
||||
deleteChannel: communication_channel_name_prefix + "_d",
|
||||
ttl: ttl,
|
||||
ctx: ctx,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *Provider[T]) Update(key string, input *T) error {
|
||||
bt, err := bson.Marshal(input)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = p.redisClient.SetEX(p.ctx, key, bt, p.ttl).Result()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = p.redisClient.Publish(p.ctx, p.updateChannel, key).Result()
|
||||
return err
|
||||
}
|
||||
|
||||
func (p *Provider[T]) Delete(key string) error {
|
||||
cnt, err := p.redisClient.Del(p.ctx, key).Result()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if cnt > 0 {
|
||||
_, err = p.redisClient.Publish(p.ctx, p.deleteChannel, key).Result()
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
Reference in New Issue
Block a user