Commit ad71b23a by 袁津

[chg]增加天气接口调用失败后三次重试机制

1 parent 8e47d0f6
...@@ -59,6 +59,11 @@ ...@@ -59,6 +59,11 @@
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId> <artifactId>spring-context-support</artifactId>
</dependency> </dependency>
<dependency>
<groupId>com.github.rholder</groupId>
<artifactId>guava-retrying</artifactId>
<version>2.0.0</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
package com.viontech.service.impl; package com.viontech.service.impl;
import java.io.IOException; import com.fasterxml.jackson.databind.DeserializationFeature;
import java.text.SimpleDateFormat; import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap; import com.github.rholder.retry.*;
import java.util.Map; import com.google.common.base.Predicates;
import com.viontech.model.*; import com.viontech.model.*;
import com.viontech.utils.HttpUtils;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.viontech.utils.HttpUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
/** /**
* @author zhaibolin * @author zhaibolin
*/ */
...@@ -25,76 +26,119 @@ import org.springframework.stereotype.Service; ...@@ -25,76 +26,119 @@ import org.springframework.stereotype.Service;
@Service @Service
public class JsonService { public class JsonService {
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
@Autowired @Autowired
private Json jsonclass; private Json jsonclass;
public SimpleWeather getWeatherInfo(int cityId) throws IOException { public SimpleWeather getWeatherInfo(int cityId) {
String json = getWeatherJson(cityId); System.out.println("城市[" + cityId + "]获取天气信息");
try {
Map<String, WeatherMessage> dataMap = new HashMap<>();
// 调用weather接口
Callable<Boolean> weatherCallable = () -> {
String host = jsonclass.getHost1();
String path = jsonclass.getPath1();
String method = "POST";
String appcode = jsonclass.getAppcode();
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "APPCODE " + appcode);
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
Map<String, String> querys = new HashMap<>();
Map<String, String> bodys = new HashMap<>();
bodys.put("cityId", String.valueOf(cityId));
HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
String json = EntityUtils.toString(response.getEntity());
System.out.println(sdf.format(new Date()) + "调用weather接口返回json:" + json);
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd")); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
WeatherMessage weatherMessage = mapper.readValue(json, WeatherMessage.class); WeatherMessage weatherMessage = mapper.readValue(json, WeatherMessage.class);
String jsons = getAqiJson(cityId); if (null != weatherMessage) {
ObjectMapper mappers = new ObjectMapper(); dataMap.put("WEATHER", weatherMessage);
mappers.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return true;
mappers.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); }
WeatherMessage weatherMessage2 = mappers.readValue(jsons, WeatherMessage.class); return false;
};
SimpleWeather simpleWeather = weathers2SimpleWeather(weatherMessage, weatherMessage2); Retryer<Boolean> weatherRetryer = RetryerBuilder.<Boolean>newBuilder()
return simpleWeather; // 发生异常时重试
} catch (IOException e) { .retryIfException()
System.out.println("json解析出错!"); // 返回false时重试
System.out.println(json); .retryIfResult(Predicates.equalTo(false))
} // 每次重试等待时间
return null; .withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS))
} // 最大重试次数
.withStopStrategy(StopStrategies.stopAfterAttempt(3))
// 记录第几次执行
.withRetryListener(new RetryListener() {
@Override
public <V> void onRetry(Attempt<V> attempt) {
System.out.println("[weather retry]times=" + attempt.getAttemptNumber());
}
})
.build();
private String getWeatherJson(int cityId) throws IOException {
String host = jsonclass.getHost1();
String path = jsonclass.getPath1();
String method = "POST";
String appcode = jsonclass.getAppcode();
Map<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "APPCODE " + appcode);
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
Map<String, String> querys = new HashMap<String, String>();
Map<String, String> bodys = new HashMap<String, String>();
bodys.put("cityId", String.valueOf(cityId));
HttpResponse response = null;
try { try {
response = HttpUtils.doPost(host, path, method, headers, querys, bodys); weatherRetryer.call(weatherCallable);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); System.out.println("城市[" + cityId + "]调用Weather接口失败");
return null;
} }
return EntityUtils.toString(response.getEntity());
}
private String getAqiJson(int cityId) throws IOException {
String host = jsonclass.getHost2(); // 调用aqi接口
String path = jsonclass.getPath2(); Callable<Boolean> aqiCallable = () -> {
String method = "POST"; String host = jsonclass.getHost2();
String appcode = jsonclass.getAppcode(); String path = jsonclass.getPath2();
Map<String, String> headers = new HashMap<String, String>(); String method = "POST";
headers.put("Authorization", "APPCODE " + appcode); String appcode = jsonclass.getAppcode();
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); Map<String, String> headers = new HashMap<>();
Map<String, String> querys = new HashMap<String, String>(); headers.put("Authorization", "APPCODE " + appcode);
Map<String, String> bodys = new HashMap<String, String>(); headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
bodys.put("cityId", String.valueOf(cityId)); Map<String, String> querys = new HashMap<>();
Map<String, String> bodys = new HashMap<>();
bodys.put("cityId", String.valueOf(cityId));
HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
String json = EntityUtils.toString(response.getEntity());
System.out.println(sdf.format(new Date()) + "调用AQI接口返回json:" + json);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
WeatherMessage aqiMessage = mapper.readValue(json, WeatherMessage.class);
if (null != aqiMessage) {
dataMap.put("AQI", aqiMessage);
return true;
}
return false;
};
Retryer<Boolean> aqiRetryer = RetryerBuilder.<Boolean>newBuilder()
// 发生异常时重试
.retryIfException()
// 返回false时重试
.retryIfResult(Predicates.equalTo(false))
// 每次重试等待时间
.withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS))
// 最大重试次数
.withStopStrategy(StopStrategies.stopAfterAttempt(3))
// 记录第几次执行
.withRetryListener(new RetryListener() {
@Override
public <V> void onRetry(Attempt<V> attempt) {
System.out.println("[aqi retry]times=" + attempt.getAttemptNumber());
}
})
.build();
HttpResponse response = null;
try { try {
response = HttpUtils.doPost(host, path, method, headers, querys, bodys); aqiRetryer.call(aqiCallable);
} catch (Exception e) { } catch (Exception e) {
// TODO Auto-generated catch block System.out.println("城市[" + cityId + "]调用AQI接口失败");
e.printStackTrace(); return null;
} }
// return response.toString();
return EntityUtils.toString(response.getEntity());
return weathers2SimpleWeather(dataMap.get("WEATHER"), dataMap.get("AQI"));
} }
private SimpleWeather weathers2SimpleWeather(WeatherMessage weatherMessage, WeatherMessage weatherMessage2) { private SimpleWeather weathers2SimpleWeather(WeatherMessage weatherMessage, WeatherMessage weatherMessage2) {
......
...@@ -56,7 +56,7 @@ public class WeatherService { ...@@ -56,7 +56,7 @@ public class WeatherService {
} }
SimpleWeather simpleWeather = jsonService.getWeatherInfo(weatherCode); SimpleWeather simpleWeather = jsonService.getWeatherInfo(weatherCode);
if (simpleWeather == null) { if (simpleWeather == null) {
System.out.println(weatherCode); // System.out.println(weatherCode);
continue; continue;
} }
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!