【问题标题】:Why does turning on @Cacheable cause my transaction to fail?为什么打开@Cacheable 会导致我的事务失败?
【发布时间】:2013-04-27 03:10:51
【问题描述】:

我想将一项服务设为可缓存。我一直在研究grails-cache plugin,它看起来很有希望,但它会导致一些我不理解的行为。

考虑以下服务:

class FooService {
    def contentService

    @Listener
    void processFoo(Foo foo) {
        doStuff(foo)
        foo.save(failOnError: true)
    }

    private void doStuff(Foo foo) {
        contentService.evaluate(foo.name)
    }
}

下面是ContentService 的定义:

class ContentService {
    Object findSource(String name) {
        Content.findByPath(name) ?: Content.findByPath(stripLocale(name))
    }

    String evaluate(String name) {
        ....
    }
}

在我尝试添加缓存之前,这一切都很好。首先,我在 Config.groovy 中进行设置:

grails.cache.config = {
    cache {
        name 'content'
    }
}

然后在我的 ContentService 中,我注释我的方法:

@Cacheable('content')
Object findSource(String name) {
    Content.findByPath(name) ?: Content.findByPath(stripLocale(name))
}

进行这些更改后,我的processFoo 方法成功执行了每一行代码,然后在退出时抛出其中一个:

非法 arg 调用 java.lang.reflect.InvocationTargetException org.springframework.transaction.UnexpectedRollbackException: 事务回滚,因为它已被标记为仅回滚

最让我困惑的是我的FooService 甚至没有调用带有@Cacheable 注释的方法。仅调用了evaluate() 方法,并且该方法似乎没有问题。为什么将此注解添加到本次执行中甚至未使用的方法会导致事务回滚?

【问题讨论】:

  • 在将grails.cache.proxyTargetClass 配置选项设置为true 时,您是否看到相同的行为?
  • @Andrew:是的,开启此设置的行为相同。
  • @Samo 你有没有发现这种行为的原因?
  • @Thihara 我不记得了!

标签: caching grails rollback spring-transactions


【解决方案1】:

您的 FooService 和 ContentService 真的需要在事务中表现吗?如果没有,请尝试通过将以下行添加到您的服务类来禁用服务的事务行为,看看是否有帮助:

static transactional = false

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    • 2019-11-26
    相关资源
    最近更新 更多