MONGODB之天气

该博客介绍了如何使用Java通过HTTP API获取MongoDB中的天气数据,并利用Redis进行缓存,提高查询效率。代码中展示了获取天气信息的路径,定义了天气结果的模板,并通过HttpClient进行网络请求。此外,还涉及到Redis的键值操作以及JSON解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//天气路径
public static final String WEATHER_PATH=“http://t.weather.sojson.com/api/weather/city/”;
//天气返回的模板
public static String WEATHER_RESULT=“今天是{0},{1},天气{2},{3},{4},风向{5},风力{6},日出时间{7},日落时间{8},注意{9}”;

public String findweather(String cityCode){
Object weather = redisTemplate.opsForValue().get(ConstantConf.WEATHER_CITY+cityCode);
String string="";
if(weather==null||weather.equals("")) {
string = HttpClientUtil.get2(ConstantConf.WEATHER_PATH,cityCode);
redisTemplate.opsForValue().set(ConstantConf.WEATHER_LOCK+cityCode, “lock”, ConstantConf.WEATHER_TIME, TimeUnit.SECONDS);
}else {
weather = redisTemplate.opsForValue().get(ConstantConf.WEATHER_CITY+cityCode);
}
JSONObject parseObject = JSON.parseObject(string);
JSONObject data = parseObject.getJSONObject(“data”);
JSONArray forecast = data.getJSONArray(“forecast”);
WeatherBean object = forecast.getObject(0, WeatherBean.class);
String format = MessageFormat.format(ConstantConf.WEATHER_RESULT, object.getYmd(),object.getWeek(),object.getType(),object.getHigh(),object.getLow(),object.getFx(),object.getFl(),object.getSunrise(),object.getSunset(),object.getNotice());
return format;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值