【发布时间】:2020-08-05 13:41:49
【问题描述】:
我正在用一个简单的用例实现 Ehcache,但我无法使其在 @Service 层上工作。不知道怎么回事。
这是我的服务类:
@Service
public class AccountsServiceImpl implements AccountsService {
private final AccountsRepository reactiveAccountsRepository;
@Autowired
public AccountsServiceImpl(AccountsRepository reactiveAccountsRepository){
this.reactiveAccountsRepository = reactiveAccountsRepository;
}
@Override
@Cacheable(value = "accounts", key = "#root.methodName")
public Mono<AccountsListResponse> getAccounts(String codeType) {
return reactiveAccountsRepository.findByCodeType(codeType).map(this::convertToAccountsListResponse);
}
@Cacheable(value = "accounts", key = "#root.methodName")
private AccountsListResponse convertToAccountsListResponse(Accounts accounts){
return AccountsListResponse.builder().accounts(accounts.getCodeList().stream()
.map(codes->AccountsResponse.builder().code(codes.getCode()).description(codes.getDescription())
.build()).collect(Collectors.toList()))
.build();
}
}
ehcache.xml:
<config
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns='http://www.ehcache.org/v3'
xmlns:jsr107='http://www.ehcache.org/v3/jsr107'>
<cache alias="accounts">
<expiry>
<none/>
</expiry>
<resources>
<heap unit="entries">10000</heap>
</resources>
</cache>
</config>
将此行添加到 application.properties
#eh-cache
spring.cache.jcache.config=classpath:ehcache.xml
@SpringBootApplication
@EnableReactiveCouchbaseRepositories
@EnableCaching
public class AccountsApplication{
public static void main(String[] args) {
SpringApplication.run(AccountsApplication.class, args);
}
}
Pom 依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
</dependency>
我看到控制台,似乎它已创建:
2020-04-22 10:23:39.664 INFO 16512 --- [ main] org.ehcache.core.EhcacheManager : Cache 'accounts' created in EhcacheManager. 2020-04-22 10:23:40.056 INFO 16512 --- [ main] org.ehcache.jsr107.Eh107CacheManager : Registering Ehcache MBean javax.cache:type=CacheStatistics,CacheManager=file./C./Proyectos/Core/core-accounts-boot/target/classes/ehcache.xml,Cache=accounts 2020-04-22 10:23:40.064 INFO 16512 --- [ main] org.ehcache.jsr107.Eh107CacheManager : Registering Ehcache MBean javax.cache:type=CacheStatistics,CacheManager=file./C./Proyectos/Core/core-accounts-boot/target/classes/ehcache.xml,Cache=accounts
但是在测试时它总是去数据库检索数据。我错过了什么吗?谢谢!
【问题讨论】:
-
你为什么要使用? key = "#root.methodName"
标签: java spring spring-boot caching ehcache-3