- Implement BatchGenerateWeatherArtsWorker to handle batch processing of weather art generation. - Create GenerateWeatherArtWorker for individual weather art generation tasks. - Update Dockerfile to include redis-tools for Sidekiq support. - Modify Gemfile to add sidekiq and sidekiq-scheduler gems. - Configure Sidekiq in initializers and set up routes for Sidekiq dashboard. - Include a sidekiq.yml configuration for scheduling jobs. - Create compose.yaml for Docker services including web, database, Redis, and Sidekiq workers. These changes introduce background processing capabilities using Sidekiq, allowing for efficient generation of weather art through scheduled and managed job queues, optimizing performance and scalability.
45 lines
1.1 KiB
Ruby
45 lines
1.1 KiB
Ruby
class GenerateWeatherArtWorker
|
|
|
|
def perform(*args)
|
|
city = args[0]
|
|
return if city.last_weather_fetch&.today?
|
|
|
|
weather_service = WeatherService.new
|
|
ai_service = AiService.new
|
|
|
|
# 获取天气数据
|
|
weather_data = weather_service.get_weather(city.latitude, city.longitude)
|
|
return unless weather_data
|
|
|
|
# 生成提示词
|
|
prompt = ai_service.generate_prompt(city, weather_data)
|
|
return unless prompt
|
|
|
|
# 生成图像
|
|
image_url = ai_service.generate_image(prompt)
|
|
return unless image_url
|
|
|
|
# 创建天气艺术记录
|
|
weather_art = city.weather_arts.create!(
|
|
weather_date: Date.today,
|
|
**weather_data,
|
|
prompt: prompt
|
|
)
|
|
|
|
# 下载并附加图像
|
|
tempfile = Down.download(image_url)
|
|
weather_art.image.attach(
|
|
io: tempfile,
|
|
filename: "#{city.country.name}-#{city.name.parameterize}-#{Time.current.strftime('%Y%m%d-%H%M%S')}.png"
|
|
)
|
|
|
|
# 更新城市状态
|
|
city.update!(
|
|
last_weather_fetch: Time.current,
|
|
last_image_generation: Time.current
|
|
)
|
|
rescue => e
|
|
Rails.logger.error "Error generating weather art for #{city.name}: #{e.message}"
|
|
end
|
|
end
|