package com.moral.api.service.impl; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.ObjectUtils; import com.moral.api.entity.CityWeather; import com.moral.api.mapper.CityWeatherMapper; import com.moral.api.service.CityWeatherService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.moral.constant.RedisConstants; import com.moral.util.WeatherUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.HashMap; import java.util.Map; /** *

* 城市实测小时气象数据表 服务实现类 *

* * @author moral * @since 2021-10-28 */ @Service public class CityWeatherServiceImpl extends ServiceImpl implements CityWeatherService { @Autowired RedisTemplate redisTemplate; @Autowired CityWeatherMapper cityWeatherMapper; @Override public Map queryWeatherByRegionCode(Integer regionCode) { Map value = (Map) redisTemplate.opsForHash().get(RedisConstants.CITY_WEATHER,String.valueOf(regionCode)); if(value==null) value = queryCityWeatherByRegionCodeFromDB(regionCode); return value; } @Override public Map dressingIndex(Map map) { Map resultMap = new HashMap<>(); int city_code = Integer.parseInt(map.get("regionCode").toString()); String time = ""; Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - 2); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH"); time = sdf.format(calendar.getTime())+":00:00"; QueryWrapper cityWeatherQueryWrapper = new QueryWrapper<>(); cityWeatherQueryWrapper.eq("city_code",city_code); cityWeatherQueryWrapper.eq("time",time); CityWeather cityWeather = cityWeatherMapper.selectOne(cityWeatherQueryWrapper); if (ObjectUtils.isEmpty(cityWeather)){ return resultMap; } JSONObject jsonObject = JSONObject.parseObject(cityWeather.getValue()); Map weatherMap = new HashMap<>(); weatherMap.put("temp",jsonObject.get("temp")); weatherMap.put("humidity",jsonObject.get("humidity")); weatherMap.put("windScale",jsonObject.get("windScale")); resultMap = WeatherUtils.dressingIndex(weatherMap); return resultMap; } /** * @Description: 从数据库查询天气数据 * @Param: [regionCode] * @return: java.util.Map * @Author: 陈凯裕 * @Date: 2021/10/29 */ private Map queryCityWeatherByRegionCodeFromDB(Integer regionCode) { QueryWrapper wrapper = new QueryWrapper(); wrapper.eq("city_code",regionCode); wrapper.orderByDesc("time"); wrapper.last(true,"limit 1"); CityWeather weather = cityWeatherMapper.selectOne(wrapper); if(weather==null) return null; String value = weather.getValue(); redisTemplate.opsForHash().put(RedisConstants.CITY_WEATHER,regionCode,value); return JSON.parseObject(value,Map.class); } }