{"id":10008257,"date":"2023-09-09T23:52:46","date_gmt":"2023-09-09T15:52:46","guid":{"rendered":"https:\/\/blog.itmax.cn\/?p=10008257"},"modified":"2023-09-09T23:52:46","modified_gmt":"2023-09-09T15:52:46","slug":"%e8%81%8a%e8%81%8aspring%e7%9a%84transactionsynchronizationadapter","status":"publish","type":"post","link":"https:\/\/itmax.cn\/?p=10008257","title":{"rendered":"\u804a\u804aspring\u7684TransactionSynchronizationAdapter"},"content":{"rendered":"<h2>\u5e8f<\/h2>\n<p>\u672c\u6587\u4e3b\u8981\u7814\u7a76\u4e00\u4e0bspring\u7684TransactionSynchronizationAdapter<\/p>\n<h2>\u793a\u4f8b\u4ee3\u7801<\/h2>\n<pre><code>public void insert(TechBook techBook){\n        bookMapper.insert(techBook);\n       \/\/ send after tx commit but is async\n        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {\n            @Override\n            public void afterCommit() {\n                System.out.println(&quot;send email after transaction commit...&quot;);\n            }\n        }\n       );\n        System.out.println(&quot;service end&quot;);\n    }<\/code><\/pre>\n<blockquote><p>\u4f7f\u7528TransactionSynchronizationManager.registerSynchronization\u6ce8\u518c\u4e86\u4e00\u4e2aTransactionSynchronizationAdapter\uff0c\u5728\u5176afterCommit\u65b9\u6cd5\u4e5f\u5c31\u662f\u4e8b\u52a1\u63d0\u4ea4\u6210\u529f\u4e4b\u540e\u6267\u884c\u4e00\u4e9b\u989d\u5916\u903b\u8f91<\/p><\/blockquote>\n<h2>TransactionSynchronizationAdapter<\/h2>\n<p>org\/springframework\/transaction\/support\/TransactionSynchronizationAdapter.java<\/p>\n<pre><code>public abstract class TransactionSynchronizationAdapter implements TransactionSynchronization, Ordered {\n\n    @Override\n    public int getOrder() {\n        return Ordered.LOWEST_PRECEDENCE;\n    }\n\n    @Override\n    public void suspend() {\n    }\n\n    @Override\n    public void resume() {\n    }\n\n    @Override\n    public void flush() {\n    }\n\n    @Override\n    public void beforeCommit(boolean readOnly) {\n    }\n\n    @Override\n    public void beforeCompletion() {\n    }\n\n    @Override\n    public void afterCommit() {\n    }\n\n    @Override\n    public void afterCompletion(int status) {\n    }\n\n}<\/code><\/pre>\n<blockquote><p>TransactionSynchronizationAdapter\u662f\u4e2a\u62bd\u8c61\u7c7b\uff0c\u58f0\u660e\u5b9e\u73b0TransactionSynchronization\u53caOrdered\u63a5\u53e3<\/p><\/blockquote>\n<h2>TransactionSynchronization<\/h2>\n<p>org\/springframework\/transaction\/support\/TransactionSynchronization.java<\/p>\n<pre><code>    \/**\n     * Invoked after transaction commit. Can perform further operations right\n     * &lt;i&gt;after&lt;\/i&gt; the main transaction has &lt;i&gt;successfully&lt;\/i&gt; committed.\n     * &lt;p&gt;Can e.g. commit further operations that are supposed to follow on a successful\n     * commit of the main transaction, like confirmation messages or emails.\n     * &lt;p&gt;&lt;b&gt;NOTE:&lt;\/b&gt; The transaction will have been committed already, but the\n     * transactional resources might still be active and accessible. As a consequence,\n     * any data access code triggered at this point will still &quot;participate&quot; in the\n     * original transaction, allowing to perform some cleanup (with no commit following\n     * anymore!), unless it explicitly declares that it needs to run in a separate\n     * transaction. Hence: &lt;b&gt;Use {@code PROPAGATION_REQUIRES_NEW} for any\n     * transactional operation that is called from here.&lt;\/b&gt;\n     * @throws RuntimeException in case of errors; will be &lt;b&gt;propagated to the caller&lt;\/b&gt;\n     * (note: do not throw TransactionException subclasses here!)\n     *\/\n    default void afterCommit() {\n    }<\/code><\/pre>\n<blockquote><p>\u6ce8\u610f\u8fd9\u91cc\u6ce8\u91ca\u8bf4\u660e\u4e86\u5f02\u5e38\u4e0d\u4f1a\u88ab\u6355\u83b7\uff0c\u800c\u4e14\u5efa\u8bae\u4e0d\u5728\u8fd9\u91cc\u629b\u51faTransactionException\u7684\u5b50\u7c7b\uff1b\u53e6\u5916\u5bf9\u4e8eafterCommit\u6709\u6570\u636e\u5e93\u76f8\u5173\u64cd\u4f5c\u7684\u5efa\u8bae\u4f7f\u7528PROPAGATION_REQUIRES_NEW\u8fd9\u4e2a\u4e8b\u52a1\u4f20\u64ad\u7ea7\u522b\uff0c\u4e0d\u7136afterCommit\u7684\u64cd\u4f5c\u53ef\u80fd\u4e0d\u4f1a\u751f\u6548<\/p><\/blockquote>\n<h2>registerSynchronization<\/h2>\n<p>org\/springframework\/transaction\/support\/TransactionSynchronizationManager.java<\/p>\n<pre><code>\n    private static final ThreadLocal&lt;Set&lt;TransactionSynchronization&gt;&gt; synchronizations =\n            new NamedThreadLocal&lt;&gt;(&quot;Transaction synchronizations&quot;);\n\n    \/**\n     * Register a new transaction synchronization for the current thread.\n     * Typically called by resource management code.\n     * &lt;p&gt;Note that synchronizations can implement the\n     * {@link org.springframework.core.Ordered} interface.\n     * They will be executed in an order according to their order value (if any).\n     * @param synchronization the synchronization object to register\n     * @throws IllegalStateException if transaction synchronization is not active\n     * @see org.springframework.core.Ordered\n     *\/\n    public static void registerSynchronization(TransactionSynchronization synchronization)\n            throws IllegalStateException {\n\n        Assert.notNull(synchronization, &quot;TransactionSynchronization must not be null&quot;);\n        Set&lt;TransactionSynchronization&gt; synchs = synchronizations.get();\n        if (synchs == null) {\n            throw new IllegalStateException(&quot;Transaction synchronization is not active&quot;);\n        }\n        synchs.add(synchronization);\n    }<\/code><\/pre>\n<blockquote><p>TransactionSynchronizationManager\u7684registerSynchronization\u65b9\u6cd5\u4f1a\u628aTransactionSynchronization\u6ce8\u518c\u5230\u5f53\u524d\u7ebf\u7a0b\u7684synchronizations<\/p><\/blockquote>\n<h2>processCommit<\/h2>\n<p>org\/springframework\/transaction\/support\/AbstractPlatformTransactionManager.java<\/p>\n<pre><code>private void processCommit(DefaultTransactionStatus status) throws TransactionException {\n        try {\n            boolean beforeCompletionInvoked = false;\n\n            try {\n                boolean unexpectedRollback = false;\n                prepareForCommit(status);\n                triggerBeforeCommit(status);\n                triggerBeforeCompletion(status);\n                beforeCompletionInvoked = true;\n\n                if (status.hasSavepoint()) {\n                    if (status.isDebug()) {\n                        logger.debug(&quot;Releasing transaction savepoint&quot;);\n                    }\n                    unexpectedRollback = status.isGlobalRollbackOnly();\n                    status.releaseHeldSavepoint();\n                }\n                else if (status.isNewTransaction()) {\n                    if (status.isDebug()) {\n                        logger.debug(&quot;Initiating transaction commit&quot;);\n                    }\n                    unexpectedRollback = status.isGlobalRollbackOnly();\n                    doCommit(status);\n                }\n                else if (isFailEarlyOnGlobalRollbackOnly()) {\n                    unexpectedRollback = status.isGlobalRollbackOnly();\n                }\n\n                \/\/ Throw UnexpectedRollbackException if we have a global rollback-only\n                \/\/ marker but still didn't get a corresponding exception from commit.\n                if (unexpectedRollback) {\n                    throw new UnexpectedRollbackException(\n                            &quot;Transaction silently rolled back because it has been marked as rollback-only&quot;);\n                }\n            }\n            catch (UnexpectedRollbackException ex) {\n                \/\/ can only be caused by doCommit\n                triggerAfterCompletion(status, TransactionSynchronization.STATUS_ROLLED_BACK);\n                throw ex;\n            }\n            catch (TransactionException ex) {\n                \/\/ can only be caused by doCommit\n                if (isRollbackOnCommitFailure()) {\n                    doRollbackOnCommitException(status, ex);\n                }\n                else {\n                    triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN);\n                }\n                throw ex;\n            }\n            catch (RuntimeException | Error ex) {\n                if (!beforeCompletionInvoked) {\n                    triggerBeforeCompletion(status);\n                }\n                doRollbackOnCommitException(status, ex);\n                throw ex;\n            }\n\n            \/\/ Trigger afterCommit callbacks, with an exception thrown there\n            \/\/ propagated to callers but the transaction still considered as committed.\n            try {\n                triggerAfterCommit(status);\n            }\n            finally {\n                triggerAfterCompletion(status, TransactionSynchronization.STATUS_COMMITTED);\n            }\n\n        }\n        finally {\n            cleanupAfterCompletion(status);\n        }\n    }\n\n    private void triggerAfterCommit(DefaultTransactionStatus status) {\n        if (status.isNewSynchronization()) {\n            if (status.isDebug()) {\n                logger.trace(&quot;Triggering afterCommit synchronization&quot;);\n            }\n            TransactionSynchronizationUtils.triggerAfterCommit();\n        }\n    }<\/code><\/pre>\n<blockquote><p>AbstractPlatformTransactionManager\u7684processCommit\u65b9\u6cd5\uff0c\u5728\u63d0\u4ea4\u6210\u529f\u4e4b\u540e\u89e6\u53d1triggerAfterCommit\uff0c\u8fd9\u91cc\u8c03\u7528\u4e86TransactionSynchronizationUtils.triggerAfterCommit()\uff0c\u6ce8\u610f\u8fd9\u91cc\u6ca1\u6709try catch\uff0c\u8bf4\u660etriggerAfterCommit\u7684\u5f02\u5e38\u6700\u7ec8\u4f1a\u629b\u7ed9\u8c03\u7528\u65b9<\/p><\/blockquote>\n<h2>triggerAfterCommit<\/h2>\n<p>org\/springframework\/transaction\/support\/TransactionSynchronizationUtils.java<\/p>\n<pre><code>    public static void triggerAfterCommit() {\n        invokeAfterCommit(TransactionSynchronizationManager.getSynchronizations());\n    }\n\n    public static void invokeAfterCommit(@Nullable List&lt;TransactionSynchronization&gt; synchronizations) {\n        if (synchronizations != null) {\n            for (TransactionSynchronization synchronization : synchronizations) {\n                synchronization.afterCommit();\n            }\n        }\n    }<\/code><\/pre>\n<blockquote><p>\u8fd9\u91cc\u904d\u5386synchronizations\u6267\u884cafterCommit\u65b9\u6cd5\uff0c\u5982\u679c\u5176\u4e2d\u6709\u4e00\u4e2a\u6709\u5f02\u5e38\u629b\u51fa\u5219\u4e2d\u65ad<\/p><\/blockquote>\n<h2>\u5c0f\u7ed3<\/h2>\n<p>\u4f7f\u7528TransactionSynchronizationManager.registerSynchronization\u53ef\u4ee5\u5728\u5f53\u524d\u7ebf\u7a0b\u7684\u4e8b\u52a1\u6ce8\u518c\u4e00\u4e2aTransactionSynchronizationAdapter\uff0c\u53ef\u4ee5\u5728afterCommit\u65b9\u6cd5\u4e5f\u5c31\u662f\u4e8b\u52a1\u63d0\u4ea4\u6210\u529f\u4e4b\u540e\u6267\u884c\u4e00\u4e9b\u989d\u5916\u903b\u8f91\uff1b\u6ce8\u610f\u8fd9\u91cc\u629b\u51fa\u7684\u5f02\u5e38\u4e0d\u5f71\u54cd\u4e8b\u52a1\u63d0\u4ea4\uff0c\u4f46\u662f\u5f02\u5e38\u4e0d\u4f1a\u88abcatch\u9700\u8981\u7531\u8c03\u7528\u65b9\u5904\u7406\uff0c\u5bf9\u4e8eafterCommit\u6709\u6570\u636e\u5e93\u76f8\u5173\u64cd\u4f5c\u7684\u5efa\u8bae\u4f7f\u7528PROPAGATION_REQUIRES_NEW\u8fd9\u4e2a\u4e8b\u52a1\u4f20\u64ad\u7ea7\u522b\uff0c\u4e0d\u7136afterCommit\u7684db\u64cd\u4f5c\u53ef\u80fd\u4e0d\u4f1a\u751f\u6548\u3002<\/p>\n<blockquote><p>\u5728\u4e8b\u52a1\u63d0\u4ea4\u4e4b\u540e\u505a\u4e00\u4e9b\u4e8b\u60c5\u53ef\u80fd\u4e0d\u9700\u8981TransactionSynchronizationManager.registerSynchronization\u8fd9\u79cd\u65b9\u5f0f\u4e5f\u80fd\u5b9e\u73b0\uff0c\u4e5f\u5c31\u662f\u9700\u8981\u989d\u5916\u4e00\u5c42\u6765\u8c03\u7528\u4e8b\u52a1\u64cd\u4f5c\uff0c\u6709\u5f02\u5e38\u4f1a\u629b\u51fa\uff0c\u6ca1\u6709\u5f02\u5e38\u5219\u6267\u884c\u4e8b\u52a1\u63d0\u4ea4\u4e4b\u540e\u7684\u4e8b\u60c5\uff0c\u524d\u63d0\u5c31\u662f\u4e8b\u52a1\u56de\u6eda\u5f02\u5e38\u4e0d\u80fd\u88ab\u541e\u6389\uff0c\u4e0d\u7136\u5916\u5c42\u8c03\u7528\u53ef\u80fd\u4ee5\u4e3a\u4e8b\u52a1\u6210\u529f\u4e86<br \/>\u8fd8\u6709\u4e00\u79cd\u65b9\u5f0f\u5c31\u662f\u4f7f\u7528TransactionalEventListener\uff0c\u8fd9\u79cd\u65b9\u5f0f\u6bd4TransactionSynchronizationManager.registerSynchronization\u66f4\u4e3a\u4f18\u96c5\u4e00\u4e9b<\/p><\/blockquote>\n<h2>doc<\/h2>\n<ul>\n<li><a target=\"_blank\" href=\"https:\/\/segmentfault.com\/a\/1190000004235193\" rel=\"noopener noreferrer\">\u5982\u4f55\u5728\u6570\u636e\u5e93\u4e8b\u52a1\u63d0\u4ea4\u6210\u529f\u540e\u8fdb\u884c\u5f02\u6b65\u64cd\u4f5c<\/a><\/li>\n<li><a target=\"_blank\" href=\"https:\/\/link.segmentfault.com\/?enc=ajRwX7MSJEec2gkzBGSYfw%3D%3D.P4x4Zlx5UmOvYpLhPjOcgyt4bZnJJXOl7K%2F8cLOk1nB%2BrLYVYQaR%2FlFLMyBfrwrB\" rel=\"noopener noreferrer\">Spring\u4e8b\u52a1aftercommit\u539f\u7406\u53ca\u5b9e\u8df5<\/a><\/li>\n<\/ul>\n<p><a href=\"https:\/\/segmentfault.com\/a\/1190000044200286\">https:\/\/segmentfault.com\/a\/1190000044200286<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u5e8f \u672c\u6587\u4e3b\u8981\u7814\u7a76\u4e00\u4e0bspring\u7684TransactionSynchronizationAdapter \u793a\u4f8b\u4ee3\u7801 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[4],"tags":[],"class_list":["post-10008257","post","type-post","status-publish","format-standard","hentry","category-share"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/posts\/10008257","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=10008257"}],"version-history":[{"count":0,"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/posts\/10008257\/revisions"}],"wp:attachment":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=10008257"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=10008257"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=10008257"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}