2015-07-22 62 views
4

我在SpringBoot應用程序的服務中有一個簡單的方法。我使用@Retryable爲該方法設置了重試機制。
我正在嘗試服務中的方法的集成測試,並且當方法拋出異常時不會發生重試。該方法只執行一次。@Retryable在集成測試觸發時未進行重試在Spring Boot應用程序中

public interface ActionService { 

@Retryable(maxAttempts = 3, backoff = @Backoff(delay = 2000)) 
public void perform() throws Exception; 

} 



@Service 
public class ActionServiceImpl implements ActionService { 

@Override 
public void perform() throws Exception() { 

    throw new Exception(); 
    } 
} 



@SpringBootApplication 
@Import(RetryConfig.class) 
public class MyApp { 

public static void main(String[] args) throws Exception { 
    SpringApplication.run(MyApp.class, args); 
    } 
} 



@Configuration 
@EnableRetry 
public class RetryConfig { 

@Bean 
public ActionService actionService() { return new ActionServiceImpl(); } 

} 



@RunWith(SpringJUnit4ClassRunner.class) 
@SpringApplicationConfiguration(classes= {MyApp.class}) 
@IntegrationTest({"server.port:0", "management.port:0"}) 
public class MyAppIntegrationTest { 

@Autowired 
private ActionService actionService; 

public void testAction() { 

    actionService.perform(); 

} 
+0

我不認爲'@ Retryable'被繼承。嘗試將它移動到bean服務方法而不是接口方法 –

回答

4

你的註釋@EnableRetry是在錯誤的地方,而不是把它ActionService界面上,你應該用一個基於的Spring Java @Configuration類放置,在這種情況下與MyApp類。通過這種更改,重試邏輯應該按預期工作。這裏是我寫過的博客文章,如果你對更多細節感興趣 - http://biju-allandsundry.blogspot.com/2014/12/spring-retry-ways-to-integrate-with.html

+0

這是一個SpringBoot應用程序,除了接口本身之外,我應該將Service作爲配置中的Bean來使用。 我已更新與我的更改的帖子。它仍然不起作用。 – user3451476

+0

我測試了你的類,它對我很好,'actionService'被調用了三次,然後返回一個異常,嘗試在你的執行方法中打印一些東西,看它多次調用。 –

0

Biju感謝你爲此提供了一個鏈接,它幫助我解決了很多問題。我唯一需要分開的是我仍然必須在基於spring xml的方法中將'retryAdvice'添加爲bean,還必須確保啓用了上下文註釋,並且可以在classpath中使用aspectj。在我在下面添加這些之後,我可以開始工作。

<bean id="retryAdvice" 
    class="org.springframework.retry.interceptor.RetryOperationsInterceptor"> 
</bean> 

<context:annotation-config /> 
<aop:aspectj-autoproxy /> 
+0

'@ Configuration'與''相同,'@ EnableAspectJAutoProxy'與''相同,'@ EnableRetry'添加'@ EnableAspectJAutoProxy'。添加'spring-boot-starter-aop'作爲依賴提供'aspectjweaver'。 – WhiteKnight

相關問題