WeatherService.java 2.96 KB
package com.viontech.service.impl;

import com.viontech.model.City;
import com.viontech.model.Mall;
import com.viontech.model.SimpleWeather;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author zhaibolin
 */
@Service
public class WeatherService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private JsonService jsonService;

    @Autowired
    private CityService cityService;

    public void getWeatherInfo() throws IOException {
        // 摆子哥之前为啥这样写?
        // Date date = java.sql.Date.valueOf(LocalDate.now());
        Date date = Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant());
        System.out.println(LocalDateTime.now() + "天气服务调用开始");
        List<Mall> mallList = cityService.selectMallList();
        List<City> cityList = cityService.selectCityList(mallList);
        Set<Integer> cityIds = new HashSet<>(cityService.selectTodayWeather(date));
        if (!cityList.isEmpty()) {
            for (City bcity : cityList) {
                if (cityIds.contains(bcity.getCityId())) {
                    System.out.println("" + bcity.getCityName() + "天气已经存在");
                    continue;
                }
                Integer weatherCode = null;
                try {
                    if (bcity.getWeatherCode() == null) {
                        continue;
                    }
                    weatherCode = new Integer(bcity.getWeatherCode().trim());
                } catch (NumberFormatException e) {
                    continue;
                }
                SimpleWeather simpleWeather = jsonService.getWeatherInfo(weatherCode);
                if (simpleWeather == null) {
                    System.out.println(weatherCode);
                    continue;
                }

                jdbcTemplate.update(
                        "insert into d_weather(province_id,city_id,type,data_date,ltemp,htemp,aqi,modify_time,create_time,wind_intensity) values(?,?,?,?,?,?,?,NOW(),NOW(),?);",
                        bcity.getProvinceId(),
                        bcity.getCityId(),
                        String.valueOf(simpleWeather.getType()),
                        date,
                        Integer.parseInt(simpleWeather.getLtemp()),
                        Integer.parseInt(simpleWeather.getHtemp()),
                        Integer.parseInt(simpleWeather.getAqi()),
                        Integer.parseInt(simpleWeather.getFengli().substring(0, 1))
                );
                System.out.println(bcity.getCityName() + "天气插入成功");
            }
        }
        System.out.println("天气服务调用结束");
    }
}