feat: 添加微服务模板基础架构
- 创建基于 CloudWego Hertz 的 Go 微服务脚手架 - 集成 Nacos 服务注册/发现功能 - 添加 gRPC 客户端支持 - 实现环境变量配置管理 (.env.example) - 添加 HTTP 中间件 (Recovery, AccessLog, CORS) - 配置 Gitea CI/CD 构建部署流程 BREAKING CHANGE: 项目结构调整,从简单的 API 服务升级为完整的微服务架构
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
package redis_tools
|
||||
|
||||
import (
|
||||
"apiServer_service/utils/logger"
|
||||
"context"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-redis/redis/v8"
|
||||
)
|
||||
|
||||
var (
|
||||
client *redis.Client
|
||||
once sync.Once
|
||||
)
|
||||
|
||||
func ConnectRedis() *redis.Client {
|
||||
once.Do(func() {
|
||||
addr := os.Getenv("REDIS_HOST")
|
||||
if addr == "" {
|
||||
addr = "127.0.0.1:6379"
|
||||
}
|
||||
password := os.Getenv("REDIS_PASSWORD")
|
||||
|
||||
client = redis.NewClient(&redis.Options{
|
||||
Addr: addr,
|
||||
Password: password,
|
||||
DB: 0,
|
||||
PoolSize: 20,
|
||||
MinIdleConns: 5,
|
||||
DialTimeout: 5 * time.Second,
|
||||
ReadTimeout: 3 * time.Second,
|
||||
WriteTimeout: 3 * time.Second,
|
||||
})
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := client.Ping(ctx).Err(); err != nil {
|
||||
logger.Warn("Redis", "连接失败: ", err)
|
||||
return
|
||||
}
|
||||
logger.Info("Redis", "连接成功")
|
||||
})
|
||||
return client
|
||||
}
|
||||
|
||||
func GetClient() *redis.Client {
|
||||
return ConnectRedis()
|
||||
}
|
||||
|
||||
func Close() error {
|
||||
if client != nil {
|
||||
return client.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ---- List 操作 ----
|
||||
|
||||
func AddToList(key string, value interface{}) error {
|
||||
return GetClient().LPush(context.Background(), key, value).Err()
|
||||
}
|
||||
|
||||
func GetListRange(key string, start, stop int64) ([]string, error) {
|
||||
return GetClient().LRange(context.Background(), key, start, stop).Result()
|
||||
}
|
||||
|
||||
func GetAllFromList(key string) ([]string, error) {
|
||||
return GetListRange(key, 0, -1)
|
||||
}
|
||||
|
||||
func RemoveFromList(key string, value interface{}) error {
|
||||
return GetClient().LRem(context.Background(), key, 0, value).Err()
|
||||
}
|
||||
|
||||
// ---- KV 缓存操作 ----
|
||||
|
||||
func SetCache(key string, value interface{}, expiration time.Duration) error {
|
||||
return GetClient().Set(context.Background(), key, value, expiration).Err()
|
||||
}
|
||||
|
||||
func GetCache(key string) (string, error) {
|
||||
return GetClient().Get(context.Background(), key).Result()
|
||||
}
|
||||
|
||||
func Exists(key string) bool {
|
||||
n, err := GetClient().Exists(context.Background(), key).Result()
|
||||
return err == nil && n > 0
|
||||
}
|
||||
|
||||
func Del(keys ...string) error {
|
||||
return GetClient().Del(context.Background(), keys...).Err()
|
||||
}
|
||||
Reference in New Issue
Block a user