第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Spring 的當前線程中禁止 @Transactional

在 Spring 的當前線程中禁止 @Transactional

慕慕森 2021-12-10 10:27:00
我正在尋找下一個問題的解決方案。我使用 Spring 并且我有一些不應(yīng)被阻止的執(zhí)行程序線程(至少讀/寫數(shù)據(jù)庫)。有幾個任務(wù)可以通過這個執(zhí)行器執(zhí)行,我不知道哪個可以使用@Transactional方法或任何其他方式來訪問數(shù)據(jù)庫。我想禁止在執(zhí)行者線程中打開新事務(wù),怎么做?小例子@Componentpublic class Service {    public void execute() {        System.out.println("I don't need transaction to execute");    }}@Componentpublic class Service2 {    @Transactional    public void execute() {        System.out.println("I've opened new transaction!");    }}@Componentpublic class NonTransactionalExecutor {    @Autowired    private ThreadPoolExecutor threadPoolExecutor;    @Autowired    private Service service;    @@Autowired    private Service2 service2;    public void doInExecutor() {        threadPoolExecutor.execute(new Runnable() {            @Override            public void run() {                // Is there anything I could do to get exception on service2.execute?                service.execute();                service2.execute();            }        });    }}PS 在現(xiàn)實世界中,當方法被注釋時,@Transactional它會嘗試TransactionManager使用數(shù)據(jù)庫中的當前值打開新事務(wù)(我使用的是 Postgres)。
查看完整描述

1 回答

?
智慧大石

TA貢獻1946條經(jīng)驗 獲得超3個贊

您可能可以為此使用裝飾器模式。實現(xiàn)您自己的PlatformTransactionManager并將您當前的經(jīng)理作為委托傳遞給它。在 中g(shù)etTransaction,如果當前線程不是您所期望的,則拋出異常。


public class MyTransactionManager implements PlatformTransactionManager {

    private final PlatformTransactionManager delegate;


    public MyTransactionManager(PlatformTransactionManager delegate) {

        this.delegate = delegate;

    }


    @Override

    public void commit(TransactionStatus status) {

        delegate.commit(status);

    }


    @Override

    public TransactionStatus getTransaction(TransactionDefinition definition) {

        if (Thread.getCurrentThread() == /*something*/) {

            return delegate.getTransaction(definition);

        }

        else {

            throw new RuntimeException();

        }

    }


    @Override

    public void rollback(TransactionStatus status) {

        delegate.rollback(status);

    }

}


查看完整回答
反對 回復(fù) 2021-12-10
  • 1 回答
  • 0 關(guān)注
  • 358 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號