feat: init repo
This commit is contained in:
44
backend/providers/redis/config.go
Normal file
44
backend/providers/redis/config.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.ipao.vip/rogeecn/atom/container"
|
||||
"git.ipao.vip/rogeecn/atom/utils/opt"
|
||||
)
|
||||
|
||||
const DefaultPrefix = "Redis"
|
||||
|
||||
func DefaultProvider() container.ProviderContainer {
|
||||
return container.ProviderContainer{
|
||||
Provider: Provide,
|
||||
Options: []opt.Option{
|
||||
opt.Prefix(DefaultPrefix),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Host string
|
||||
Port uint
|
||||
Password string
|
||||
DB uint
|
||||
}
|
||||
|
||||
func (c *Config) format() {
|
||||
if c.Host == "" {
|
||||
c.Host = "localhost"
|
||||
}
|
||||
|
||||
if c.Port == 0 {
|
||||
c.Port = 6379
|
||||
}
|
||||
|
||||
if c.DB == 0 {
|
||||
c.DB = 0
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Config) Addr() string {
|
||||
return fmt.Sprintf("%s:%d", c.Host, c.Port)
|
||||
}
|
||||
33
backend/providers/redis/provider.go
Normal file
33
backend/providers/redis/provider.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"git.ipao.vip/rogeecn/atom/container"
|
||||
"git.ipao.vip/rogeecn/atom/utils/opt"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func Provide(opts ...opt.Option) error {
|
||||
o := opt.New(opts...)
|
||||
var config Config
|
||||
if err := o.UnmarshalConfig(&config); err != nil {
|
||||
return err
|
||||
}
|
||||
config.format()
|
||||
return container.Container.Provide(func() (redis.UniversalClient, error) {
|
||||
rdb := redis.NewClient(&redis.Options{
|
||||
Addr: config.Addr(),
|
||||
Password: config.Password,
|
||||
DB: int(config.DB),
|
||||
})
|
||||
|
||||
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
if _, err := rdb.Ping(ctx).Result(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return rdb, nil
|
||||
}, o.DiOptions()...)
|
||||
}
|
||||
Reference in New Issue
Block a user