如何根据异常更改Spring Retry模板固定的退回策略

问题描述

我正在使用Spring Retry模板进行重试。

这是我的重试方法,这里我的重试间隔应基于Exception。例如,如果抛出DataException,则重试应间隔1000(1秒);如果抛出MQException,则重试应间隔5000(5秒)。

如何根据异常更改FixedBackOffPolicy实例。

主要流程:

private void retrytest(){
                retryTemplate.execute(context -> {
                    log.info("Processing request...");
                    retryTest1();
                    return true; 
                },context -> {
                    log.info("Recovering request...");
                    return true;
                });

    }  

private void retryTest1(){
    throw new DataException("Data exception"); 
     //throw new MQException("MQ Message exception"); 
}

重试模板初始化:

@Bean
    public RetryTemplate retryTemplate() {
        RetryTemplate retryTemplate = new RetryTemplate();

        FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
        fixedBackOffPolicy.setBackOffPeriod(1000L);
        retryTemplate.setBackOffPolicy(new CustomBackOffPolicy());  // Custom backoff policy 

        SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
        retryPolicy.setMaxAttempts(5);
        retryTemplate.setRetryPolicy(retryPolicy);

        
        return retryTemplate;
    }


public class CustomBackOffPolicy implements BackOffPolicy {

    @Autowired
    RetryTemplate retryTemplate;


    @Override
    public BackOffContext start(RetryContext retryContext) {
          RetryPolicy retryPolicy = (RetryPolicy) retryContext;

          return null;
    }

    @Override
    public void backOff(BackOffContext backOffContext) throws BackOffInterruptedException {
        try {
            Thread.sleep(1000l);
        } catch (InterruptedException var2) {
            throw new BackOffInterruptedException("Thread interrupted while sleeping",var2);
        }
    }

解决方法

您将需要自定义import React from 'react'; import axios from 'axios'; import {BrowserRouter as Router,Switch,Route,Redirect} from 'react-router-dom'; import Login from "./pages/Login"; import Home from "./pages/Home"; import Profile from "./pages/Profile"; import Register from "./pages/Register"; import Header from "./components/Header"; import Administration from "./pages/Administration"; import './assets/main.css' import './App.css' import PrivateRoute from "./components/PrivateRoute"; import Category from "./pages/Category"; import Product from "./pages/Product"; import Order from "./pages/Order"; import User from "./pages/User"; import Support from "./pages/Support"; export default class App extends React.Component { constructor(props) { super(props); this.state = { redirectToHome: false,isLog: false,isAdmin: false,user: null,} } componentDidMount(){ if (localStorage.getItem('token')){ axios.post('auth/me') .then((res) => { this.setUser(res.data) }) .catch((err) => { localStorage.removeItem('token') }) } } setUser = (user) => { this.setState({user: user}) } render() { if (this.state.redirectToHome){ return <Redirect to={'/'} from={'/logout'} /> } return ( <Router> <div> <Header user={this.state.user} setUser={this.setUser} /> </div> <div className="mx-10"> <Switch> <Route exact path="/" component={() => <Home user={this.state.user} />} /> <Route exact path="/login" component={() => <Login setUser={this.setUser} />} /> <Route exact path="/profile" component={() => <Profile user={this.state.user}/>} /> <Route exact path="/register" component={Register} /> <PrivateRoute exact path="/admin" component={() => <Administration user={this.state.user} />} /> <PrivateRoute exact path="/admin/categories" component={() => <Category />} /> <PrivateRoute exact path="/admin/products" component={() => <Product />} /> <PrivateRoute exact path="/admin/orders" component={() => <Order />} /> <PrivateRoute exact path="/admin/users" component={() => <User />} /> <PrivateRoute exact path="/admin/supports" component={() => <Support />} /> </Switch> </div> </Router> ); } }; ;您可以通过BackOffPolicy方法中的RetryContext获取异常类型。

您可以使用类似于start()中使用的技术,该技术根据异常类型委派不同的重试策略。