Add redis driver

Signed-off-by: Asai Neko <sugar@sne.moe>
This commit is contained in:
2025-12-25 14:51:45 +08:00
parent 9e51414a13
commit 32a27d974a
9 changed files with 90 additions and 4 deletions

View File

@@ -3,11 +3,13 @@ package data
import (
"nixcn-cms/data/drivers"
"github.com/redis/go-redis/v9"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
var Database *drivers.DBClient
var Redis *redis.UniversalClient
func Init() {
// Init database
@@ -34,6 +36,20 @@ func Init() {
if err != nil {
log.Error("[Database] Error migrating database: ", err)
}
Database = db
// Init redis conection
rdbAddress := viper.GetStringSlice("cache.hosts")
dsn := drivers.RedisDSN{
Hosts: rdbAddress,
Master: viper.GetString("cache.master"),
Username: viper.GetString("cache.username"),
Password: viper.GetString("cache.password"),
DB: viper.GetInt("cache.db"),
}
rdb, err := drivers.Redis(dsn)
if err != nil {
log.Fatal("[Redis] Error connecting to Redis: ", err)
}
Redis = rdb
}

22
data/drivers/redis.go Normal file
View File

@@ -0,0 +1,22 @@
package drivers
import (
"context"
"github.com/redis/go-redis/v9"
)
func Redis(dsn RedisDSN) (*redis.UniversalClient, error) {
// Connect to Redis
rdb := redis.NewUniversalClient(&redis.UniversalOptions{
Addrs: dsn.Hosts,
MasterName: dsn.Master,
Username: dsn.Username,
Password: dsn.Password,
DB: dsn.DB,
})
ctx := context.Background()
// Ping Redis
_, err := rdb.Ping(ctx).Result()
return &rdb, err
}

View File

@@ -11,6 +11,14 @@ type ExternalDSN struct {
Password string
}
type RedisDSN struct {
Hosts []string
Master string
Username string
Password string
DB int
}
type DBClient struct {
*gorm.DB
}

16
data/event.go Normal file
View File

@@ -0,0 +1,16 @@
package data
import (
"time"
"github.com/google/uuid"
)
type Event struct {
Id uint `json:"id" gorm:"primarykey;autoincrement"`
UUID uuid.UUID `json:"uuid" gorm:"type:uuid;uniqueindex;not null"`
EventId uuid.UUID `json:"event_id" gorm:"type:uuid;uniqueindex;not null"`
Name string `json:"name" gorm:"type:varchar(255);index;not null"`
StartTime time.Time `json:"start_time" gorm:"index"`
EndTime time.Time `json:"end_time" gorm:"index"`
}

View File

@@ -10,12 +10,12 @@ type User struct {
Id uint `json:"id" gorm:"primarykey;autoincrement"`
UUID uuid.UUID `json:"uuid" gorm:"type:uuid;uniqueindex;not null"`
UserId uuid.UUID `json:"user_id" gorm:"type:uuid;uniqueindex;not null"`
Email string `json:"email" gorm:"uniqueindex;not null"`
Type string `json:"type" gorm:"not null"`
Email string `json:"email" gorm:"type:varchar(255);uniqueindex;not null"`
Type string `json:"type" gorm:"type:varchar(32);index;not null"`
Nickname string `json:"nickname"`
Subtitle string `json:"subtitle"`
Avatar string `json:"avatar"`
Checkin time.Time `json:"checkin"`
Checkin time.Time `json:"checkin" gorm:"index"`
}
func (self *User) GetByEmail(email string) error {