gpt4 book ai didi

java - 如何在缓存的分页结果中添加新的或更新的对象

转载 作者:行者123 更新时间:2023-12-02 02:31:57 26 4
gpt4 key购买 nike

如何更新缓存分页列表中的对象?当您创建对象时,它会在分页列表中返回,但执行更新后,分页列表中返回的对象不会更改。

类配置ehCache

@Configuration
@EnableCaching
public class EhCacheConfiguration {

@Bean
public CacheManager cacheManager() {
return new EhCacheCacheManager(cacheManagerFactory().getObject());
}

@Bean
public EhCacheManagerFactoryBean cacheManagerFactory() {
EhCacheManagerFactoryBean bean = new EhCacheManagerFactoryBean();
bean.setConfigLocation(new ClassPathResource("ehcache.xml"));
bean.setShared(true);
return bean;
}
}

文件 ehCache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd">
<cache name="contaCache"
maxEntriesLocalHeap="100"
timeToLiveSeconds="3600">
</cache>
</ehcache>

我的服务如下所示:

@Service
public class ContaGerencialServiceImpl implements ContaGerencialService {
private ContaGerencialRepository repository;

@Autowired
public ContaGerencialServiceImpl(ContaGerencialRepository repository) {
this.repository = repository;
}


@Override
@Cacheable(value = "contaCache", key = "#pageable.pageNumber")
public Page<ContaGerencial> listPageable(Pageable pageable) {
return repository.findAll(pageable);
}

@Override
@CachePut(value = "contaCache", key = "#conta.id")
public ContaGerencial save(ContaGerencial conta) {
return repository.save(conta);
}

@Override
@CachePut(value = "contaCache", key = "#conta.id")
public ContaGerencial update(ContaGerencial conta) {
return repository.save(conta);
}
}

Json 新对象:

{
"numero":"102030",
"nome":"Conta Gerencial 1"
}

分页列表:

{
"content": [
{
"id": 2,
"nome": "Conta Gerencial 1",
"numero": "102030",
"dataCadastro": "2019-07-26T00:00:00.000-0300",
"dataUltimaAtualizacao": "2019-07-26T00:00:00.000-0300"
}
],

...

}

Json 更新

{
"id": 2,
"numero": "222",
"nome": "Conta Gerencial"
}

但是列表中的分页结果是一样的。如何在返回时更新对象?谢谢。

最佳答案

以类似的方式使用注释@cacheable通过id缓存记录。更新时,您必须使用注释@CacheEvict清除缓存。

    @Override
@Cacheable(value = "contaCache", key = "#pageable.pageNumber")
public Page<ContaGerencial> listPageable(Pageable pageable) {
return repository.findAll(pageable);
}

@Override
@CachePut(value = "contaCache", key = "#conta.id")
public ContaGerencial save(ContaGerencial conta) {
return repository.save(conta);
}

@Override
@CachePut(value = "contaCache", key = "#conta.id")
public ContaGerencial update(ContaGerencial conta) {
return repository.save(conta);
}

@CacheEvict(value = "contaCache", key = "#id")
public void evictSingleCacheValue(String id) {
}

@CacheEvict(value = "contaCache", key = "#pageable.pageNumber")
public void evictListPageable(Pageable pageable) {
}

关于java - 如何在缓存的分页结果中添加新的或更新的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57224673/

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