标签: spring-cache

spring-data-couchbase 为不存在的文档抛出 DocumentDoesNotExistException

我使用spring-data-couchbase 2.1.2spring-boot 1.4.0.RC1couchbase-spring-cache

当缓存被禁用时它工作正常,因为它返回 NULL 对象当缓存被启用并尝试在存储桶中查找不存在的文档时,它会引发异常:

com.couchbase.client.java.error.DocumentDoesNotExistException: null
    at com.couchbase.client.java.CouchbaseAsyncBucket$22.call(CouchbaseAsyncBucket.java:684) ~[java-client-2.2.8.jar:na]
    at com.couchbase.client.java.CouchbaseAsyncBucket$22.call(CouchbaseAsyncBucket.java:671) ~[java-client-2.2.8.jar:na]
    at rx.internal.operators.OperatorMap$1.onNext(OperatorMap.java:54) ~[rxjava-1.0.17.jar:1.0.17]
    at rx.observers.Subscribers$5.onNext(Subscribers.java:234) ~[rxjava-1.0.17.jar:1.0.17]
    at rx.subjects.SubjectSubscriptionManager$SubjectObserver.onNext(SubjectSubscriptionManager.java:223) ~[rxjava-1.0.17.jar:1.0.17]
    at rx.subjects.AsyncSubject.onCompleted(AsyncSubject.java:101) ~[rxjava-1.0.17.jar:1.0.17]
    at com.couchbase.client.core.endpoint.AbstractGenericHandler.completeResponse(AbstractGenericHandler.java:354) ~[core-io-1.2.9.jar:na]
    at com.couchbase.client.core.endpoint.AbstractGenericHandler.access$000(AbstractGenericHandler.java:72) ~[core-io-1.2.9.jar:na]
    at com.couchbase.client.core.endpoint.AbstractGenericHandler$1.call(AbstractGenericHandler.java:372) ~[core-io-1.2.9.jar:na]
    at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55) ~[rxjava-1.0.17.jar:1.0.17]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) ~[na:1.7.0_80]
    at java.util.concurrent.FutureTask.run(FutureTask.java:262) ~[na:1.7.0_80]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:178) ~[na:1.7.0_80]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:292) ~[na:1.7.0_80]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) ~[na:1.7.0_80]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) ~[na:1.7.0_80]
    at java.lang.Thread.run(Thread.java:745) ~[na:1.7.0_80]
Caused by: rx.exceptions.OnErrorThrowable$OnNextValue: OnError while emitting onNext value: com.couchbase.client.core.message.kv.RemoveResponse.class
    at rx.exceptions.OnErrorThrowable.addValueAsLastCause(OnErrorThrowable.java:109) ~[rxjava-1.0.17.jar:1.0.17]
    at rx.exceptions.Exceptions.throwOrReport(Exceptions.java:188) ~[rxjava-1.0.17.jar:1.0.17]
    at …
Run Code Online (Sandbox Code Playgroud)

java spring spring-boot spring-cache spring-data-couchbase

3
推荐指数
1
解决办法
1417
查看次数

Spring缓存@CacheEvict匹配列表中的键?

我正在使用 Spring 缓存并尝试通过键(id)列表逐出缓存。

@CacheEvict(value="cacheName",key=?, condition=? )
public void deleteByIds(List<Integer> ids){...}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

java spring spring-cache

3
推荐指数
1
解决办法
7681
查看次数

使用Spring Cacheable的L1 + L2缓存策略

我正在尝试设置 L1 + L2 缓存策略以与@Cacheable注释一起使用。我的目标是

  1. 配置咖啡因缓存
  2. 配置Redis缓存
  3. 在 Caffeine Cache 中查找项目,如果找到则返回,否则执行步骤 4
  4. 在Redis缓存中查找项目,如果找到则返回并缓存在caffeine中,否则执行第5步
  5. 使用真实服务返回结果。

我知道这不受开箱即用的支持,但我一直在尝试阅读有关如何连接此类解决方案的文档。

我当前的解决方案是将我的实际服务包装在RedisBackedService具有注释的 a 中,而该服务又包装在具有注释的a 中。不用说,这似乎是多余的。redisCacheManagercacheableCaffeineBackedServicecaffeineCacheManagercacheable

任何指示都会有帮助。

spring-data-redis spring-boot spring-cache caffeine

3
推荐指数
1
解决办法
2364
查看次数

无需 XML 配置即可将 Ehcache CacheManager (v 3.x) 转换为 Spring CacheManager

我正在尝试在我的应用程序中使用 Ehcache 管理器。我想在没有 xml 配置的情况下设置它。我有下一个依赖项:

<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>3.6.0</version>
</dependency>
<dependency>
    <groupId>javax.cache</groupId>
    <artifactId>cache-api</artifactId>
    <version>1.0.0</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>5.1.1.RELEASE</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

我有这样的 CacheManager bean:

@Bean
public org.springframework.cache.CacheManager cacheManager() {
    org.ehcache.CacheManager mainPageCache = CacheManagerBuilder
            .newCacheManagerBuilder()
            .withCache("mainPageCache", CacheConfigurationBuilder
                    .newCacheConfigurationBuilder(
                            Pageable.class,
                            Collection.class,
                            ResourcePoolsBuilder.heap(10))
                    .withExpiry(ExpiryPolicyBuilder
                            .timeToLiveExpiration(Duration
                                    .of(10, ChronoUnit.SECONDS))))
            .build(true);
    // ...
}
Run Code Online (Sandbox Code Playgroud)

是否可以将 Ehcache CacheManager 转换为 Spring CacheManager?我认为应该是这样的:return new JCacheCacheManager(/*some code*/);

java spring ehcache spring-cache ehcache-3

3
推荐指数
1
解决办法
3645
查看次数

如何在 Spring Boot 中使用控制器/服务上的缓存?

我正在尝试按照https://www.java4s.com/spring-boot-tutorials/how-to-configure-cache-in-spring-boot-applications/ 上的说明在我的 spring-boot 应用程序上添加缓存,但它不起作用。我不完全确定如何测试它。我在控制器下有一个 system.out.print 就像这篇文章一样。如果缓存有效,那么它只会打印“测试”一次,但从具有相同输入的请求中返回相同的结果。我的代码如下:

货币控制器.java

    @RequestMapping(method = RequestMethod.POST)
    @Cacheable(value="currency")
    public ResponseEntity getExchangedCurrency(final @RequestBody CurrencyExchange currencyExchange) {
        System.out.println("Test");
        return ResponseEntity.ok()
              .headers(responseHeaders)
              .body(currencyService.calculate(currencyExchange));
    }

Run Code Online (Sandbox Code Playgroud)

应用程序.java

@SpringBootApplication
@EnableCaching
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);



    }
}

Run Code Online (Sandbox Code Playgroud)

java spring-boot spring-cache

3
推荐指数
1
解决办法
3104
查看次数

Spring Redis 缓存中的 ClassCastException

我正在使用 Spring Boot 版本 2.1.8.RELEASE 开发 Spring Boot 应用程序。我需要构建自定义 RedisCacheManager。

RedisCacheManager如下。

@EnableCaching
@Configuration
class CacheConfig {
    @Bean
    fun redisCacheManager(lettuceConnectionFactory: RedisConnectionFactory): RedisCacheManager? {
        val redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofHours(1))

        return RedisCacheManager.RedisCacheManagerBuilder
            .fromConnectionFactory(lettuceConnectionFactory)
            .cacheDefaults(redisCacheConfiguration)
            .build()
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的服务中,我使用 @Cacheble 缓存响应。看:

@Cacheable(cacheNames = ["cached_sample"])
    fun getAllSample(): List<SampleRecord> {
        return auditableRepository.findAll()
    }
Run Code Online (Sandbox Code Playgroud)

模型我缓存:

data class SampleRecord(
    @ApiModelProperty(readOnly = true)
    val id: Long? = null,
    @ApiModelProperty(readOnly = true)
    val active: Boolean? = null,
    @ApiModelProperty(readOnly = true)
    val createdDate: Instant? = null,
    val param: String
): Serializable …
Run Code Online (Sandbox Code Playgroud)

redis spring-data redis-cache spring-boot spring-cache

3
推荐指数
1
解决办法
3293
查看次数

带有 Spring 缓存和咖啡因的 Spring 云网关

我有一个 Spring Cloud 网关,它将 API 剩余请求转发到一些微服务。

我想缓存特定请求的响应。为此我写了这个过滤器

@Component
@Slf4j
public class CacheResponseGatewayFilterFactory extends AbstractGatewayFilterFactory<CacheResponseGatewayFilterFactory.Config> {
   private final CacheManager cacheManager;

   public CacheResponseGatewayFilterFactory(CacheManager cacheManager) {
     super(CacheResponseGatewayFilterFactory.Config.class);
     this.cacheManager = cacheManager;
   }

   @Override
   public GatewayFilter apply(CacheResponseGatewayFilterFactory.Config config) {
     final var cache = cacheManager.getCache("MyCache");
     return (exchange, chain) -> {
        final var path = exchange.getRequest().getPath();
        if (nonNull(cache.get(path))) {
            log.info("Return cached response for request: {}", path);
            final var response = cache.get(path, ServerHttpResponse.class);
            final var mutatedExchange = exchange.mutate().response(response).build();
            return mutatedExchange.getResponse().setComplete();
        }

        return chain.filter(exchange).doOnSuccess(aVoid -> {
            cache.put(path, exchange.getResponse());
        }); …
Run Code Online (Sandbox Code Playgroud)

spring spring-boot spring-cache spring-cloud-gateway caffeine-cache

3
推荐指数
1
解决办法
5649
查看次数

Spring Caching密钥生成器

我刚刚开始研究Spring缓存.

我的服务方法是......

@Override
@Cacheable(value="profile", **key**="personId" )
public String cpuService2(Long personId, String personAddress){
    return "CachedMessage";
}
Run Code Online (Sandbox Code Playgroud)

没有key子句,不抛出异常并假设两个参数都自动生成缓存但是使用键,当我调用此方法时,抛出异常为...

Exception in thread "main" org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Field or property 'personId' cannot be found on object of type 'org.springframework.cache.interceptor.CacheExpressionRootObject'
        at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:246)
        at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:112)
        at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:107)
        at org.springframework.expression.spel.ast.OpGT.getValueInternal(OpGT.java:37)
        at org.springframework.expression.spel.ast.OpGT.getValueInternal(OpGT.java:29)
        at org.springframework.expression.spel.ast.SpelNodeImpl.getTypedValue(SpelNodeImpl.java:102)
        at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:98)
        at org.springframework.cache.interceptor.ExpressionEvaluator.condition(ExpressionEvaluator.java:99)
        at org.springframework.cache.interceptor.CacheAspectSupport$CacheOperationContext.isConditionPassing(CacheAspectSupport.java:462)
        at org.springframework.cache.interceptor.CacheAspectSupport$CacheOperationContext.isConditionPassing(CacheAspectSupport.java:456)
        at org.springframework.cache.interceptor.CacheAspectSupport.inspectCacheables(CacheAspectSupport.java:292)
        at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:199)
        at org.springframework.cache.interceptor.CacheInterceptor.invoke(CacheInterceptor.java:66)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
        at $Proxy5.cpuService3(Unknown Source)
        at pack100_cache.pack020CacheKey.TestSimpleBean.main(TestSimpleBean.java:34)
Run Code Online (Sandbox Code Playgroud)

搜索文档但没有任何线索.希望有人能解决这个问题.

spring caching spring-cache

2
推荐指数
2
解决办法
8314
查看次数

用于Spring Cache Manager的Junit

我在应用程序中使用Spring缓存层,在编写单元测试以使用Mockito测试Spring缓存层时遇到了一个问题。

请针对我的问题参考以下代码:

服务层:

    public CustomerServiceImpl implements CustomerService {
    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private CustomerRepository customerRepository;//Repository is simple JPA repository interface which contains findByCustomerName()

    @Override
    @CachePut(value = "#customer", key = "#customer.customerName")
    public Customer insertOrUpdate(Customer customer) {
        return customerRepository.save(customer);
    }

    @Cacheable(value="customersCache", key = "#customerName")
    public Customer findByCustomerName(String customerName) {
        Customer customer = customerRepository.findByCustomerName(customerName);
        return customer;
    }
}
Run Code Online (Sandbox Code Playgroud)

用于服务层的JUnit测试代码:

@RunWith(PowerMockRunner.class)
@PrepareForTest(CustomerServiceImplTest.class)
public class CustomerServiceImplTest {

    @Spy
    CacheManager cacheManager = new ConcurrentMapCacheManager("customersCache");

    @Mock
    CustomerRepository CustomerRepository;

    @InjectMocks
    CustomerServiceImpl customerServiceImpl = …
Run Code Online (Sandbox Code Playgroud)

java junit spring mockito spring-cache

2
推荐指数
1
解决办法
6339
查看次数

JBoss上的Spring Boot和Infinspan缓存

我已经在集群中安装并运行了JBoss 7。我正在开发一个Spring Boot 1.3.2应用程序。我在domain.xml中定义了以下Infinispan缓存:

           <cache-container name="my-cache" default-cache="auth">
                <transport stack="tcp" lock-timeout="10000"/>
                <replicated-cache name="auth" mode="SYNC" batching="true">
                    <locking isolation="REPEATABLE_READ"/>
                    <transaction mode="NONE"/>
                    <eviction strategy="LRU" max-entries="100"/>
                    <expiration max-idle="300000"/>
                </replicated-cache>
            </cache-container>
Run Code Online (Sandbox Code Playgroud)

在application.properties文件中,我定义了以下内容:

spring.cache.type=infinispan
Run Code Online (Sandbox Code Playgroud)

然后在我的缓存类中定义:

@CacheConfig(cacheNames="java:jboss/infinispan/cache/my-cache/auth")
Run Code Online (Sandbox Code Playgroud)

当我尝试在JBoss上部署应用程序时,出现以下错误:

Caused by: java.lang.IllegalArgumentException: No cache manager could be auto-configured, check your configuration (caching type is 'INFINISPAN'
Run Code Online (Sandbox Code Playgroud)

如何配置它才能正常工作?

java spring infinispan spring-boot spring-cache

2
推荐指数
1
解决办法
1177
查看次数