【发布时间】:2019-05-08 20:36:21
【问题描述】:
在调用具有来自 Spring 的 Oauth2 的 API 时,我们需要添加重试。
我们还没有想出一个简单的方法。我们甚至尝试使用拦截器,但没有运气。
这是我们的代码:
Application.java
@EnableRetry
@SpringBootApplication
public class Application {
public static void main(String args[]) {
SpringApplication.run(Application.class);
}
@Bean
public OAuth2RestTemplate oAuth2RestTemplate(ClientHttpRequestInterceptor interceptor) {
List<String> scopes = new ArrayList<>();
scopes.add("some-scope");
ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails();
resourceDetails.setAccessTokenUri("tokenUrl");
resourceDetails.setClientId("client-id");
resourceDetails.setClientSecret("client-secret");
resourceDetails.setScope(scopes);
OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resourceDetails);
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(interceptor);
oAuth2RestTemplate.setInterceptors(interceptors);
return oAuth2RestTemplate;
}
@Bean
public CommandLineRunner run(OAuth2RestTemplate oAuth2RestTemplate) throws Exception {
return args -> {
oAuth2RestTemplate.getForObject(
"some-url-that-returns-error.com", Quote.class);
};
}
}
MyInterceptor.java
@Component
public class MyInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution execution) throws IOException {
return interceptWithRetry(httpRequest, bytes, execution);
}
@Retryable
private ClientHttpResponse interceptWithRetry(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution execution) throws IOException {
System.out.println("====================================");
return execution.execute(httpRequest, bytes);
}
}
以及我们的 pom.xml 中的依赖项
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>1.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
当我们运行这个并且出现错误时,我们看不到调用 beign 重试,无论我们将什么参数传递给@Retryable,拦截器只会被调用一次。
有人可以提供一些指导吗?
谢谢
【问题讨论】:
标签: java spring-boot oauth-2.0 spring-security-oauth2 spring-retry