spring 为什么TransactionalEventServer在transaction中不起作用?

oyt4ldly  于 2023-11-16  发布在  Spring
关注(0)|答案(1)|浏览(108)

我已经实现了事件发布器,但它并不像我预期的那样工作。我试图配置事件发布仅用于成功的事务异步提交。
使用示例:

@Transactional(readOnly = true)
    public FooDto getFooByUuid(final String uuid) {
        ...findFooByUuid(uuid)...
        auditClient.publishEvent(new Event(foo)); // published only if transaction didn't rolled back.
        ... some code
        return fooDto;
    }

字符串
我有以下配置。

@Configuration
@EnableAsync
public class ApplicationConfig implements AsyncConfigurer {

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new CustomAsyncExceptionHandler();
    }

    @Bean(name = "publishPoolTaskExecutor")
    @Primary
    public Executor publishPoolTaskExecutor() {
        final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix("publisher-");
        executor.initialize();
        return executor;
    }

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}


我有审计客户端

...
    @Async(value = "publishPoolTaskExecutor")
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void publishEvent(EventDto<?> event) {
    try {
                String eventString = objectMapper.writeValueAsString(event);
                String response = restTemplate.postForEntity(
                    url,
                    eventString,
                    String.class
                ).getBody();
                log.info(response);
            } catch (Exception e) {
                ...
            }
     }


当getFooByUuid方法中抛出异常时-事件仍然发布。我应该如何配置BullshEvent方法,该方法仅在事务成功提交时执行。

sqxo8psd

sqxo8psd1#

可能是监听器无法获取交易信息的问题?尝试使用

@TransactionalEventListener(fallbackExecution = true)

字符串
如果它有帮助-这意味着在发布事件后,由于某种原因交易信息丢失

相关问题