2025-10-31 10:01:06 +00:00
|
|
|
package data
|
|
|
|
|
|
2025-11-03 07:38:27 +00:00
|
|
|
import (
|
|
|
|
|
"context"
|
2025-11-03 11:12:39 +00:00
|
|
|
"fmt"
|
2025-11-03 07:38:27 +00:00
|
|
|
"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 连接
|
2025-11-03 08:03:19 +00:00
|
|
|
func InitWeatherCache(ctx context.Context, data *config.Redis) error {
|
2025-11-03 07:38:27 +00:00
|
|
|
_redis = redis.NewClient(&redis.Options{
|
2025-11-03 08:03:19 +00:00
|
|
|
Addr: data.Addr,
|
|
|
|
|
Password: data.Password,
|
|
|
|
|
DB: data.DB,
|
|
|
|
|
ReadTimeout: data.ReadTimeout * time.Second,
|
|
|
|
|
WriteTimeout: data.WriteTimeout * time.Second,
|
|
|
|
|
PoolSize: data.PoolSize,
|
|
|
|
|
MinIdleConns: data.MinIdleConns,
|
2025-11-03 07:38:27 +00:00
|
|
|
})
|
2025-11-03 08:03:19 +00:00
|
|
|
_expire = data.Expire
|
2025-11-03 07:38:27 +00:00
|
|
|
|
|
|
|
|
_, err := _redis.Ping(ctx).Result()
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
2025-11-03 11:12:39 +00:00
|
|
|
// 设置某个地方的天气情况
|
2025-11-03 07:38:27 +00:00
|
|
|
func SetWeatherCondition(ctx context.Context, key, condition string) error {
|
2025-11-03 11:12:39 +00:00
|
|
|
redis_key := fmt.Sprintf("%s-condition", key)
|
2025-11-04 03:45:51 +00:00
|
|
|
_, err := _redis.SetNX(ctx, redis_key, condition, _expire).Result()
|
2025-11-03 07:38:27 +00:00
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 查找某个地方的天气情况
|
|
|
|
|
func GetWeatherCondition(ctx context.Context, key string) (string, error) {
|
2025-11-03 11:12:39 +00:00
|
|
|
redis_key := fmt.Sprintf("%s-condition", key)
|
|
|
|
|
value, err := _redis.Get(ctx, redis_key).Result()
|
|
|
|
|
if err == nil {
|
|
|
|
|
return value, nil
|
|
|
|
|
} else if err == redis.Nil {
|
|
|
|
|
return "", nil
|
|
|
|
|
} else {
|
|
|
|
|
return "", err
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 设置某个地方的天气预报
|
|
|
|
|
func SetDailyForecasts(ctx context.Context, key, forecasts string) error {
|
|
|
|
|
redis_key := fmt.Sprintf("%s-forecasts", key)
|
2025-11-04 03:45:51 +00:00
|
|
|
_, err := _redis.SetNX(ctx, redis_key, forecasts, _expire).Result()
|
2025-11-03 11:12:39 +00:00
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 查找某个地方的天气预报
|
|
|
|
|
func GetDailyForecasts(ctx context.Context, key string) (string, error) {
|
|
|
|
|
redis_key := fmt.Sprintf("%s-forecasts", key)
|
|
|
|
|
value, err := _redis.Get(ctx, redis_key).Result()
|
2025-11-03 07:38:27 +00:00
|
|
|
if err == nil {
|
|
|
|
|
return value, nil
|
|
|
|
|
} else if err == redis.Nil {
|
|
|
|
|
return "", nil
|
|
|
|
|
} else {
|
|
|
|
|
return "", err
|
|
|
|
|
}
|
|
|
|
|
}
|