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

标签 java spring spring-boot caching redis

我正在使用 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/

相关文章:

java - 通过 urlconnect 进行 Kerberos 凭证委托(delegate)?

java - 从 MongoDB 生成模型实体类

java - Spring 按类顺序对 bean 进行排序

Spring Boot 和 MVC : How to set default value for @RequestBody object fields from application. 属性?

spring-boot - kafka嵌入: java. io.FileNotFoundException :/tmp/kafka-7785736914220873149/replication-offset-checkpoint. tmp

java - NSIS - 在运行进程之前设置进程的工作目录

java - 如何将文本设置到位于 jFrame 内的 jPanel 内的 jTextField 中以从其他 jFrame 中

java - 如何更改 JFreeChart 上的轴值字体

java - 使用 Spring Data Jpa 中的 CrudRepository 时如何修复 NoSuchBeanDefinitionException?

java - 与 Spring Data JPA 相比,使用 Spring Data REST 有哪些优势?