2025-10-31 10:01:06 +00:00
|
|
|
|
package data
|
|
|
|
|
|
|
2025-11-03 07:38:27 +00:00
|
|
|
|
import (
|
|
|
|
|
|
"context"
|
|
|
|
|
|
"github.com/go-redis/redis/v8"
|
|
|
|
|
|
"time"
|
|
|
|
|
|
"weather_and_earthquake/internal/config"
|
|
|
|
|
|
)
|
2025-10-31 10:01:06 +00:00
|
|
|
|
|
2025-11-03 07:38:27 +00:00
|
|
|
|
var _redis *redis.Client
|
|
|
|
|
|
var _expire time.Duration
|
|
|
|
|
|
|
|
|
|
|
|
// 初始化 redis 连接
|
|
|
|
|
|
func InitWeatherCache(ctx context.Context, data *config.Data) error {
|
|
|
|
|
|
_redis = redis.NewClient(&redis.Options{
|
|
|
|
|
|
Addr: data.Redis.Addr,
|
|
|
|
|
|
Password: data.Redis.Password,
|
|
|
|
|
|
DB: data.Redis.DB,
|
|
|
|
|
|
ReadTimeout: data.Redis.ReadTimeout * time.Second,
|
|
|
|
|
|
WriteTimeout: data.Redis.WriteTimeout * time.Second,
|
|
|
|
|
|
PoolSize: data.Redis.PoolSize,
|
|
|
|
|
|
MinIdleConns: data.Redis.MinIdleConns,
|
|
|
|
|
|
})
|
|
|
|
|
|
_expire = data.Redis.Expire
|
|
|
|
|
|
|
|
|
|
|
|
_, err := _redis.Ping(ctx).Result()
|
|
|
|
|
|
return err
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 设置某个地方的天气情况,默认保留1小时数据
|
|
|
|
|
|
func SetWeatherCondition(ctx context.Context, key, condition string) error {
|
|
|
|
|
|
_, err := _redis.SetNX(ctx, key, condition, _expire*time.Second).Result()
|
|
|
|
|
|
return err
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 查找某个地方的天气情况
|
|
|
|
|
|
func GetWeatherCondition(ctx context.Context, key string) (string, error) {
|
|
|
|
|
|
value, err := _redis.Get(ctx, key).Result()
|
|
|
|
|
|
if err == nil {
|
|
|
|
|
|
return value, nil
|
|
|
|
|
|
} else if err == redis.Nil {
|
|
|
|
|
|
return "", nil
|
|
|
|
|
|
} else {
|
|
|
|
|
|
return "", err
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|