wood chen b11cf228e3 调整定时任务执行时间,优化价格更新逻辑
- 修改 InitCronJobs 函数中的定时任务执行时间,OpenRouter价格获取任务和其他厂商价格更新任务分别调整为每天06:04和06:30执行。
- 在 UpdateOtherPrices 函数中新增清除倍率缓存的逻辑,确保价格更新后缓存数据的准确性。
- 优化 GetPriceRates 函数,移除不必要的字段查询,提升查询效率。
2025-03-22 09:40:04 +08:00

81 lines
2.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package rates
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
"aimodels-prices/database"
"aimodels-prices/models"
)
// PriceRate 价格倍率结构
type PriceRate struct {
Model string `json:"model"`
ModelType string `json:"model_type"`
Type string `json:"type"`
ChannelType uint `json:"channel_type"`
Input float64 `json:"input"`
Output float64 `json:"output"`
}
// GetPriceRates 获取价格倍率
func GetPriceRates(c *gin.Context) {
cacheKey := "price_rates"
// 尝试从缓存获取
if cachedData, found := database.GlobalCache.Get(cacheKey); found {
if rates, ok := cachedData.([]PriceRate); ok {
c.JSON(http.StatusOK, rates)
return
}
}
// 使用索引优化查询,只查询需要的字段
var prices []models.Price
if err := database.DB.Select("model, billing_type, channel_type, input_price, output_price, currency, status").
Where("status = 'approved'").
Find(&prices).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch prices"})
return
}
// 预分配rates切片减少内存分配
rates := make([]PriceRate, 0, len(prices))
// 计算倍率
for _, price := range prices {
// 根据货币类型计算倍率
var inputRate, outputRate float64
if price.Currency == "USD" {
// 如果是美元除以2
inputRate = price.InputPrice / 2
outputRate = price.OutputPrice / 2
} else {
// 如果是人民币或其他货币除以14
inputRate = price.InputPrice / 14
outputRate = price.OutputPrice / 14
}
rates = append(rates, PriceRate{
Model: price.Model,
Type: price.BillingType,
ChannelType: price.ChannelType,
Input: inputRate,
Output: outputRate,
})
}
// 存入缓存有效期24小时
database.GlobalCache.Set(cacheKey, rates, 24*time.Hour)
c.JSON(http.StatusOK, rates)
}
// ClearRatesCache 清除价格倍率缓存
func ClearRatesCache() {
database.GlobalCache.Delete("price_rates")
}