前のブログでは、Spring Retryの使用を紹介しました。この記事では、簡単な例を介して春の再試行の実装原則を示しています。この例で定義されている注釈には、retry属性の数のみが含まれています。実際、春の再試行の注釈は、より多くの属性を設定することができます。原則を説明するために、それはより簡単です。春の再試行については、関連するドキュメントやブログを確認できます。
注釈定義
パッケージretry.Annotation; Import Java.lang.Annotation。*;/*** Jack.wuが2016/9/30に作成しました。 */@ターゲット(elementType.method)@retention(retentionPolicy.runtime)@documentedpublic @interface retryable {int maxattemps()default 0;}エージェントの実装
CGLIBをプロキシツールとして使用して、最初にコールバック実装を書き込みます。これは、再試行実装のコアロジックでもあります。
パッケージretry.interceptor; Import net.sf.cglib.proxy.methodinterceptor; Import net.sf.cglib.proxy.methodproxy; import retry.annotation.retryable; Import java.lang.reflect.method;/*** 2016/9/30でJack.wuによって作成されました。 */public class annotationAwareretryTetrationSoperationsInterceptorは、メソッドインターセプター{// private int timesの数を記録します= 0; @Overrideパブリックオブジェクトインターセプト(オブジェクトobj、メソッドメソッド、オブジェクト[] args、methodproxyプロキシ)スロー可能{//インターセプトされたメソッドretryable retryable = method.getannotation(retryable.class)で再生可能な注釈を取得します。 if(retryable == null){return proxy.invokesuper(obj、args); } else {// retryable annotationを使用して、例外を追加してくださいロジックint maxattemps = retryable.maxattemps(); try {proxy.invokesuper(obj、args)を返します。 } catch(throwable e){if(times ++ == maxattemps){system.out.println( "最大retriesに到達しました:" + maxattemps + "、もうretry!"); } else {system.out.println( "call" + method.getName() + "method例外、start" + times + "retry ..."); //これはInvokeSuperメソッドではないことに注意してください。InvokeSuperは現在のインターセプター処理proxy.invoke(obj、args)を終了します。 }}} nullを返します。 }}次に、プロキシクラスを作成して、AnnotationAwarerThyOperationsInterceptorをインターセプターとして使用します
パッケージretry.core; Import net.sf.cglib.proxy.enhancer; Import retry.interceptor.annotationAwarertrytorationsInterceptor;/***は2016/9/30にJack.wuによって作成されました。 */public class springretryproxy {public object newProxyInstance(Object Target){Enhancer Enhancer = new Enhancer(); Enhancer.setsuperclass(target.getClass()); Enhancer.setCallback(new AnnotationAwarerTryToperationsInterceptor()); return enthancer.create(); }}テスト
ユーザー関連のビジネス方法を使用して、上記のコードをテストします
インターフェイス定義:
パッケージファサード;/*** 2016/9/26にJack.wuによって作成されました。 */public interface userfacade {void add()スロー例外。 void query()スロー例外;}インターフェイスの実装:パッケージFACADE.IMPL;
facade.userfacade; Import retry.annotation.retryable;/***は、2016/9/26にJack.wuによって作成されました。 */public class userfacadeimplはuserfacadeを実装します{@override public void add()throws exception {system.out.println( "add user ...");新しいruntimeexception()を投げる; } @override @retryable(maxattemps = 3)public void query(){system.out.println( "query user ...");新しいruntimeexception()を投げる; }}テスト:
public class main {public static void main(string [] args)スロー例外{userfacadeimpl user = new userfacadeimpl(); // SpringRetry Proxy Test SpringRetryProxy SpringRetryProxy = new SpringRetryProxy(); userfacade u =(userfacade)springretryproxy.newproxyinstance(user); //u.add( );//no retry u.query(); //失敗したretry}}} ADDメソッドは再試行注釈を追加せず、プログラムは異常に終了し、クエリメソッドは再試行を追加し、再試行を3回設定し、実行効果は次のとおりです。
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。