Skip to content

Instantly share code, notes, and snippets.

@polster
Last active March 7, 2021 07:54
Show Gist options
  • Save polster/c72432659c651c85b2a19f38af4f4e70 to your computer and use it in GitHub Desktop.
Save polster/c72432659c651c85b2a19f38af4f4e70 to your computer and use it in GitHub Desktop.
Spring Boot Retry Policy Example
config.auth.baseUrl=https://iam.myexamples.com/auth/realms/my_Public/protocol/openid-connect/token
config.auth.userName=dummyUser
config.auth.password=test12345
config.auth.key.timeToLiveInMilliseconds=900000
config.auth.retry.startIntervalInMillis=1000
config.auth.retry.maxIntervalInMillis=10000
config.auth.retry.multiplier=2
config.auth.retry.maxAttempts=5
package com.myexamples.oauth;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import static java.util.Objects.requireNonNull;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AuthToken {
private String accessToken;
@JsonCreator
public AuthToken(@JsonProperty("access_token") String accessToken) {
this.accessToken = requireNonNull(accessToken);
}
public String getAccessToken() {
return accessToken;
}
}
package com.myexamples.oauth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Optional;
@Component
public class OAuthAccess {
private static final Logger LOG = LoggerFactory.getLogger(OAuthAccess.class);
private final OAuthSettings settings;
private final RestTemplate restTemplate;
private final RetryTemplate retryTemplate;
@Autowired
public OAuthAccess(RestTemplate restTemplate,
RetryTemplate retryTemplate,
OAuthSettings settings) {
this.settings = settings;
this.restTemplate = restTemplate;
this.retryTemplate = retryTemplate;
}
public AuthToken doRequest() {
return retryTemplate.execute(context -> {
if (context.getRetryCount() > 0) {
LOG.warn(
"Get JWT attempt number {} due to error: {}",
context.getRetryCount(),
Optional.ofNullable(context.getLastThrowable()).map(Throwable::getMessage).orElseGet(String::new)
);
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.setAcceptCharset(Collections.singletonList(StandardCharsets.UTF_8));
String formData = String.format("grant_type=client_credentials&client_id=%s&client_secret=%s",
settings.getUserName(),
settings.getPassword());
HttpEntity<String> request = new HttpEntity<>(formData, headers);
ResponseEntity<AuthToken> response = restTemplate.exchange(
settings.getBaseUrl(),
HttpMethod.POST,
request,
AuthToken.class);
return response.getBody();
});
}
}
package com.myexamples.oauth;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
@Configuration
@ComponentScan(value = { "com.myexamples.oauth" })
public class OAuthConfig {
@Bean
public RestTemplate restTemplate() {
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
stringHttpMessageConverter.setWriteAcceptCharset(false);
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(0, stringHttpMessageConverter);
return restTemplate;
}
@Bean
public RetryTemplate retryTemplate(OAuthSettings oAuthSettings) {
RetryTemplate retryTemplate = new RetryTemplate();
OAuthSettings.Retry retry = oAuthSettings.getRetry();
ExponentialBackOffPolicy policy = new ExponentialBackOffPolicy();
policy.setInitialInterval(retry.getStartIntervalInMillis());
policy.setMaxInterval(retry.getMaxIntervalInMillis());
policy.setMultiplier(retry.getMultiplier());
retryTemplate.setBackOffPolicy(policy);
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(retry.getMaxAttempts());
retryTemplate.setRetryPolicy(retryPolicy);
return retryTemplate;
}
}
package com.myexamples.oauth;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "config.auth")
public class OAuthSettings {
private String baseUrl;
private String userName;
private String password;
private Key key;
private Retry retry;
public Key getKey() {
return key;
}
public void setKey(Key key) {
this.key = key;
}
public Retry getRetry() {
return retry;
}
public void setRetry(Retry retry) {
this.retry = retry;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getBaseUrl() {
return baseUrl;
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
public static class Key {
private int timeToLiveInMilliseconds;
public int getTimeToLiveInMilliseconds() {
return timeToLiveInMilliseconds;
}
public void setTimeToLiveInMilliseconds(int timeToLiveInMilliseconds) {
this.timeToLiveInMilliseconds = timeToLiveInMilliseconds;
}
}
public static class Retry {
private int multiplier;
private int startIntervalInMillis;
private int maxIntervalInMillis;
private int maxAttempts;
public int getMultiplier() {
return multiplier;
}
public void setMultiplier(int multiplier) {
this.multiplier = multiplier;
}
public int getStartIntervalInMillis() {
return startIntervalInMillis;
}
public void setStartIntervalInMillis(int startIntervalInMillis) {
this.startIntervalInMillis = startIntervalInMillis;
}
public int getMaxIntervalInMillis() {
return maxIntervalInMillis;
}
public void setMaxIntervalInMillis(int maxIntervalInMillis) {
this.maxIntervalInMillis = maxIntervalInMillis;
}
public int getMaxAttempts() {
return maxAttempts;
}
public void setMaxAttempts(int maxAttempts) {
this.maxAttempts = maxAttempts;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment