本文整理汇总了Java中org.springframework.retry.annotation.Retryable类的典型用法代码示例。如果您正苦于以下问题:Java Retryable类的具体用法?Java Retryable怎么用?Java Retryable使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Retryable类属于org.springframework.retry.annotation包,在下文中一共展示了Retryable类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: executeGetRequestWithDelayPolicy
import org.springframework.retry.annotation.Retryable; //导入依赖的package包/类
/**
* Enforces delay policy on HTTP calls as described here:
* https://github.com/reddit/reddit/wiki/API
*
* @param request : Reddit specific request
* @return Children JSONArray
*/
@Retryable(maxAttempts = 3, backoff = @Backoff(delay = 1000))
public JSONArray executeGetRequestWithDelayPolicy(RedditRequest request) {
if (delayInMs > 0) {
try {
Thread.sleep((long) delayInMs);
} catch (InterruptedException e) {
logger.warn("Interrupted Exception thrown while enforcing delay policy", e);
}
}
ResponseEntity<String> response = restTemplate.exchange(request.generateURI(), HttpMethod.GET, request.generateHttpHeaders(), String.class);
HttpHeaders headers = response.getHeaders();
double requestsRemaining = Double.valueOf(headers.get("X-Ratelimit-Remaining").get(0));
double timeRemaining = Double.valueOf(headers.get("X-Ratelimit-Reset").get(0));
calculateDelay(requestsRemaining, timeRemaining);
lastCall = System.currentTimeMillis();
return RedditAPIUtils.shortChildrenArray(new JSONObject(response.getBody()).getJSONObject("data"));
}
示例2: sendMail
import org.springframework.retry.annotation.Retryable; //导入依赖的package包/类
@Retryable(value = NotificationException.class, backoff = @Backoff(delay = 200))
public void sendMail(
Claim claim,
String targetEmail,
String pin,
String emailTemplateId,
String reference,
String submitterName
) {
Map<String, String> parameters = aggregateParams(claim, pin, submitterName);
try {
notificationClient.sendEmail(emailTemplateId, targetEmail, parameters, reference);
} catch (NotificationClientException e) {
throw new NotificationException(e);
}
}
示例3: consume
import org.springframework.retry.annotation.Retryable; //导入依赖的package包/类
@Retryable(
value = { Exception.class },
maxAttempts = 3
)
public JSONObject consume(String serviceUri) {
try {
final String endpoint = baseUrl + "?serviceUri=" + serviceUri;
ResponseEntity<String> response = restTemplate.getForEntity(
endpoint,
String.class);
JSONObject jsonResponse = new JSONObject(response.getBody());
LOGGER.debug(jsonResponse.toString());
return jsonResponse;
} catch(Exception e) {
LOGGER.error(ExceptionUtils.getStackTrace(e));
throw e;
}
}
示例4: createFlushAgent
import org.springframework.retry.annotation.Retryable; //导入依赖的package包/类
@Retryable(maxAttempts=5, value=ApiException.class, [email protected](delay=5000))
public void createFlushAgent(String dispatcherInstanceId, String aemBaseUrl, String aemDispatcherBaseUrl,
AgentRunMode runMode) throws ApiException {
logger.info(
"Creating flush agent for dispatcher id: " + dispatcherInstanceId + ", and run mode: " + runMode.getValue());
String agentDescription = "Flush Agent for author-dispatcher " + dispatcherInstanceId;
PostAgentWithHttpInfoRequest request = agentRequestFactory.getCreateFlushAgentRequest(runMode,
getFlushAgentName(dispatcherInstanceId), agentDescription, aemDispatcherBaseUrl);
SlingApi slingApi = aemApiFactory.getSlingApi(aemBaseUrl, AgentAction.CREATE);
ApiResponse<Void> response = aemApiHelper.postAgentWithHttpInfo(slingApi, request);
logger.debug("ApiResponse status code: " + response.getStatusCode());
}
示例5: findUnpairedPublishDispatcher
import org.springframework.retry.annotation.Retryable; //导入依赖的package包/类
/**
* Looks at all Publish Dispatcher instances on the auto scaling group and retrieves the
* first one missing a pair ID tag (unpaired).
* @param instanceId the Publish instance ID
* @return Publish Dispatcher instance ID tag
* @throws NoPairFoundException if can't find unpaired Publish Dispatcher
*/
@Retryable(maxAttempts=10, value=NoPairFoundException.class, [email protected](delay=5000))
public String findUnpairedPublishDispatcher(String instanceId) throws NoPairFoundException {
String unpairedDispatcher = null;
List<EC2Instance> dispatcherIds = awsHelperService.getInstancesForAutoScalingGroup(
envValues.getAutoScaleGroupNameForPublishDispatcher());
//Filter the list to get all possible eligible candidates
dispatcherIds = dispatcherIds.stream().filter(d ->
isViablePair(instanceId, d.getInstanceId())).collect(Collectors.toList());
if(dispatcherIds.size() > 1) {
String publishAZ = awsHelperService.getAvailabilityZone(instanceId);
//If there are many candidates, then pick the one with the same AZ or else use first
unpairedDispatcher = (dispatcherIds.stream().filter(i -> i.getAvailabilityZone().equalsIgnoreCase(publishAZ))
.findFirst().orElse(dispatcherIds.get(0))).getInstanceId();
} else if (dispatcherIds.size() == 1) {
unpairedDispatcher = dispatcherIds.get(0).getInstanceId();
} else {
throw new NoPairFoundException(instanceId);
}
return unpairedDispatcher;
}
示例6: getTeam
import org.springframework.retry.annotation.Retryable; //导入依赖的package包/类
@Retryable(maxAttempts = 10, backoff = @Backoff(2000L))
@Cacheable("team")
public UgcTeam getTeam(Long id, Boolean withRoster) throws IOException {
Objects.requireNonNull(id, "ID must not be null");
Map<String, Object> vars = getVariablesMap();
vars.put("id", id);
ResponseEntity<String> responseEntity = restTemplate.getForEntity(endpoints.get("teamPage"), String.class, vars);
log.trace("[TeamPage] {}", responseEntity);
if (responseEntity.getStatusCode().is4xxClientError() || responseEntity.getStatusCode().is5xxServerError()) {
throw new CustomParameterizedException("UGC API returned status " + responseEntity.getStatusCode());
}
JsonUgcResponse response = objectMapper.readValue(clean(responseEntity.getBody()), JsonUgcResponse.class);
List<Map<String, Object>> raw = convertTabularData(response);
if (!raw.isEmpty()) {
UgcTeam team = objectMapper.convertValue(raw.get(0), UgcTeam.class);
log.debug("Team {} ({}) retrieved", team.getClanName(), team.getClanId());
if (withRoster) {
team.setRoster(getRoster(id));
}
return team;
} else {
throw new CustomParameterizedException("Could not find a team with id: " + id);
}
}
示例7: getRoster
import org.springframework.retry.annotation.Retryable; //导入依赖的package包/类
@Retryable(maxAttempts = 10, backoff = @Backoff(2000L))
@Cacheable("roster")
public List<UgcTeam.RosteredPlayer> getRoster(Long id) throws IOException {
Objects.requireNonNull(id, "ID must not be null");
Map<String, Object> vars = getVariablesMap();
vars.put("id", id);
ResponseEntity<String> responseEntity = restTemplate.getForEntity(endpoints.get("teamRoster"), String.class, vars);
log.trace("[TeamRoster] {}", responseEntity);
if (responseEntity.getStatusCode().is4xxClientError() || responseEntity.getStatusCode().is5xxServerError()) {
throw new CustomParameterizedException("UGC API returned status " + responseEntity.getStatusCode());
}
JsonUgcResponse response = objectMapper.readValue(responseEntity.getBody(), JsonUgcResponse.class);
List<UgcTeam.RosteredPlayer> result = objectMapper.convertValue(convertTabularData(response), new TypeReference<List<UgcTeam.RosteredPlayer>>() {
});
log.debug("Roster for team {} retrieved: {}", id, inflect(result.size(), "member"));
return result;
}
示例8: getLegacyPlayer
import org.springframework.retry.annotation.Retryable; //导入依赖的package包/类
@Retryable(maxAttempts = 10, backoff = @Backoff(2000L))
@Cacheable("legacyPlayer")
public UgcLegacyPlayer getLegacyPlayer(Long id) throws IOException {
Objects.requireNonNull(id, "ID must not be null");
Map<String, Object> vars = getVariablesMap();
vars.put("id64", id);
ResponseEntity<String> responseEntity = restTemplate.getForEntity(endpoints.get("teamPlayer"), String.class, vars);
log.trace("[Player] {}", responseEntity);
if (responseEntity.getStatusCode().is4xxClientError() || responseEntity.getStatusCode().is5xxServerError()) {
throw new CustomParameterizedException("UGC API returned status " + responseEntity.getStatusCode());
}
JsonUgcResponse response = objectMapper.readValue(responseEntity.getBody(), JsonUgcResponse.class);
UgcLegacyPlayer player = new UgcLegacyPlayer();
player.setId(id);
player.setTeams(objectMapper.convertValue(convertTabularData(response), new TypeReference<List<UgcLegacyPlayer.Membership>>() {
}));
return player;
}
示例9: getPlayer
import org.springframework.retry.annotation.Retryable; //导入依赖的package包/类
@Retryable(maxAttempts = 10, backoff = @Backoff(2000L))
@Cacheable("player")
public UgcPlayer getPlayer(Long id) throws IOException {
Objects.requireNonNull(id, "ID must not be null");
Map<String, Object> vars = getVariablesMap();
vars.put("id64", id);
ResponseEntity<UgcPlayer> responseEntity = restTemplate.getForEntity(endpoints.get("playerTeamCurrent"), UgcPlayer.class, vars);
log.trace("[Player] {}", responseEntity);
if (responseEntity.getStatusCode().is4xxClientError() || responseEntity.getStatusCode().is5xxServerError()) {
throw new CustomParameterizedException("UGC API returned status " + responseEntity.getStatusCode());
}
UgcPlayer player = responseEntity.getBody();
if (player != null && (player.getTeam() == null || player.getTeam().isEmpty())) {
player.setUgcPage("http://www.ugcleague.com/players_page.cfm?player_id=" + id);
}
return player;
}
示例10: getTransactions
import org.springframework.retry.annotation.Retryable; //导入依赖的package包/类
@Retryable(maxAttempts = 10, backoff = @Backoff(2000L))
@Cacheable("transactions")
public List<UgcTransaction> getTransactions(String ladder, Long days) throws IOException {
Objects.requireNonNull(ladder, "Ladder must not be null");
Objects.requireNonNull(days, "Days span must not be null");
UgcLadder ladderSpec = ladderAliases.get(ladder.toLowerCase());
if (ladderSpec == null) {
throw new CustomParameterizedException("Invalid ladder name: " + ladder + ". Use one of: " +
ladderAliases.keySet().stream().collect(Collectors.joining(", ")));
}
Long ladderId = ladderSpec.getLadderId();
Map<String, Object> vars = getVariablesMap();
vars.put("ladder", ladderId);
vars.put("span", days);
ResponseEntity<String> responseEntity = restTemplate.getForEntity(endpoints.get("transactions"), String.class, vars);
log.trace("[Transactions] {}", responseEntity);
if (responseEntity.getStatusCode().is4xxClientError() || responseEntity.getStatusCode().is5xxServerError()) {
throw new CustomParameterizedException("Returned status " + responseEntity.getStatusCode());
}
JsonUgcResponse response = objectMapper.readValue(responseEntity.getBody(), JsonUgcResponse.class);
return objectMapper.convertValue(convertTabularData(response), new TypeReference<List<UgcTransaction>>() {
});
}
示例11: validate
import org.springframework.retry.annotation.Retryable; //导入依赖的package包/类
@Retryable(include = {IOException.class}, backoff = @Backoff(2000L))
private Document validate(Parameters parameters) throws IOException {
if (!enabled) {
return new Document("");
}
if (session.isEmpty()) {
if (!login()) {
// failed login at this point most likely means incorrect credentials
throw new IOException("Login could not be completed");
}
}
// our session might have expired
rateLimiter.acquire();
Document document = Jsoup.connect(parameters.getUrl())
.userAgent(USER_AGENT)
.timeout(TIMEOUT)
.data(parameters.getVariables())
.cookies(session)
.get();
if (isLoginPage(document)) {
session.clear();
throw new IOException("Remote session has expired"); // but will retry
}
return document;
}
示例12: getServerInfo
import org.springframework.retry.annotation.Retryable; //导入依赖的package包/类
/**
* Retrieves information about the <code>server</code> not essential for Source/RCON socket creation but for associated
* services like an FTP server operating for the server's location.
*
* @param subId the internal id GameServers uses for its servers
* @return a map with configuration key-values found in the GS web page
* @throws IOException if the web operation could not be completed
*/
@Retryable(backoff = @Backoff(2000L))
public Map<String, String> getServerInfo(String subId) throws IOException {
Map<String, String> map = new HashMap<>();
Document document = validate(getPanelView(subId, "server_information"));
Result result = extractResult(document.select("td.content_main").text());
if (result != Result.OTHER) {
map.put("error", result.toString());
}
Elements infos = document.select("div.server_info > a");
String surl = infos.first().text();
if (surl.startsWith("ftp://")) {
URL url = new URL(surl);
map.put("ftp-hostname", url.getHost());
String[] userInfo = Optional.ofNullable(url.getUserInfo()).orElse("").split(":");
if (userInfo.length == 2) {
map.put("ftp-username", userInfo[0]);
map.put("ftp-password", userInfo[1]);
}
}
return map;
}
示例13: refreshUserSessions
import org.springframework.retry.annotation.Retryable; //导入依赖的package包/类
@Retryable(include = OptimisticLockingFailureException.class, maxAttempts = 10)
private void refreshUserSessions(String mail) {
List<Session> cleanables = sessionRepo.findByMail(mail).stream()
.filter(session -> !isTokenInProxy(session.getToken()))
.collect(Collectors.toList());
logger.debug("will remove {} sessions for mail {}", cleanables.size(), mail);
sessionRepo.deleteAll(cleanables);
}
示例14: removeSkills
import org.springframework.retry.annotation.Retryable; //导入依赖的package包/类
@Retryable(include = OptimisticLockingFailureException.class, maxAttempts = 10)
public void removeSkills(String username, String skillName)
throws UserNotFoundException, SkillNotFoundException, EmptyArgumentException {
if (StringUtils.isEmpty(username) || StringUtils.isEmpty(skillName)) {
logger.debug("Failed to modify skills: username or skillName empty");
throw new EmptyArgumentException("arguments must not be empty or null");
}
User user = UserRepository.findByIdIgnoreCase(username);
if (user == null) {
logger.debug("Failed to remove {}'s skills: user not found", username);
throw new UserNotFoundException("user not found");
}
if (skillRepository.findByName(skillName) == null) {
logger.debug("Failed to remove {}'s skill {}: skill not found", username, skillName);
throw new SkillNotFoundException("skill not found");
}
user.removeSkill(skillName);
UserRepository.save(user);
}
示例15: getServerConfig
import org.springframework.retry.annotation.Retryable; //导入依赖的package包/类
@Retryable(backoff = @Backoff(2000L))
public synchronized Map<String, String> getServerConfig(String subId) throws IOException {
rateLimiter.acquire();
Map<String, String> map = new HashMap<>();
Document document = validateSessionAndGet(
Jsoup.connect(SUB_URL)
.userAgent(Constants.USER_AGENT)
.data("view", "server_configuration")
.data("SUBID", subId)
.timeout(TIMEOUT));
Result result = extractResult(document.select("td.content_main").text());
if (result != Result.SUCCESSFUL) {
map.put("result", result.name());
}
Elements elements = document.select("input");
for (Element el : elements) {
map.put(el.attr("name"), el.attr("value"));
}
return map;
}