Using AOP to realize the re-invocation of business services (2)

 To undertake the re-invocation of business services with AOP (1), we continue to......

 

Implementation of service retry

       Solution A: There are many actions and services in the web business system. If you start directly from each point where the service is called, there will be many modification points, and the code will be redundant, so the implementation code is not complicated.

 

try{
    //service call
} catch(UncategorizedSQLException e) {
    if(retry) {
        //service call
    }
}

 

 

       Solution B: Because we use spring, we naturally think of AOP, intercepting the call of the service method through the interceptor, and retrying the call of the service method once an UncategorizedSQLException occurs. Go directly to the code:

 

import java.lang.reflect.Method;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.framework.ReflectiveMethodInvocation;
import org.springframework.dao.DataIntegrityViolationException;

public class ServiceRetryAdvice implements MethodInterceptor {
	
	private static ThreadLocal<Integer> retryNum = new ThreadLocal<Integer>() {  
        public Integer initialValue() {  
            return 0;  
        }  
    };

	public Object invoke(MethodInvocation invocation) throws Throwable {
				
		Object returnObject = null;
		try{
			returnObject = invocation.proceed();
		} catch(DataIntegrityViolationException e) {
			
			if (retryNum.get() == 0){
				retryNum.set(1);

				ReflectiveMethodInvocation refInvocation = (ReflectiveMethodInvocation)invocation;
				Object proxy = refInvocation.getProxy();
				Method method = refInvocation.getMethod();
				Object[] args = refInvocation.getArguments();
				
				returnObject = method.invoke(proxy, args);
			} else {
				throw e;
			}
		} finally {
			retryNum.remove();
		}
		return returnObject;
	}
}

 

For a detailed description of the code and various aspects to consider, please refer to

 

Using AOP to realize the re-invocation of business services (3)

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326404939&siteId=291194637