gpt4 book ai didi

java - 从 spring boot 测试调用的@Caching 方法[用@Transactional 注释] 不起作用

转载 作者:可可西里 更新时间:2023-11-01 11:23:48 25 4
gpt4 key购买 nike

我正在使用 redis 缓存和 spring boot 注释[@Cacheable 和@CahePut],我制作了 RedisManager transactionAware,它将使用外部事务[缓存层的调用者]

@Bean
public RedisCacheManager cacheManager() {
RedisCacheManager rcm =
RedisCacheManager.builder(redisConnectionFactory())
.cacheDefaults(cacheConfiguration())
.transactionAware()
.build();
return rcm;
}

在进行如下测试时,我使用的是嵌入式 redis-:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureTestDatabase
@Transactional
public class RoleServiceImplTest extends TestingProfile {

@Before
public void setup() throws Exception {
//setup server and services

redisServer = new RedisServer(redisPort);
redisServer.start();
}
@Test
public void getUsersForRoleForTemplateRole() {
// call to caching layer methods directly annotated with @Cachable
}

...两次 [带和不带 @Transactional] spring 都毫无异常(exception)地调用 cache.put(key,result) 但它只在没有 @Transactional 的情况下保留值。

在互联网上找不到太多信息,感谢提前提供的任何帮助。

最佳答案

简而言之,只需将 @CommitRollback(false) 注释放在您的类或测试方法上即可。

在测试方法之后,Spring 默认回滚每个事务。

https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#testcontext-tx

In the TestContext framework, transactions are managed by the TransactionalTestExecutionListener, which is configured by default, even if you do not explicitly declare @TestExecutionListeners on your test class. To enable support for transactions, however, you must configure a PlatformTransactionManager bean in the ApplicationContext that is loaded with @ContextConfiguration semantics (further details are provided later). In addition, you must declare Spring’s @Transactional annotation either at the class or the method level for your tests.

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/context/transaction/TransactionalTestExecutionListener.html

Declarative Rollback and Commit Behavior

By default, test transactions will be automatically rolled back after completion of the test; however, transactional commit and rollback behavior can be configured declaratively via the @Commit and @Rollback annotations at the class level and at the method level.

关于java - 从 spring boot 测试调用的@Caching 方法[用@Transactional 注释] 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54791008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com