【问题标题】:Spring cache does not cache anythingSpring缓存不缓存任何东西
【发布时间】:2019-03-16 07:19:18
【问题描述】:

我使用的是 spring-boot-starter-parent 2.0.1 版

这些是 application.properties

spring.cache.type=redis
spring.cache.cache-names=edges
spring.cache.redis.cache-null-values=false 
spring.cache.redis.time-to-live=60000000 
spring.cache.redis.key-prefix=true 
spring.redis.host=localhost 
spring.redis.port=6379

这是主类。

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

这是我要缓存它的结果的java方法。

@Service
public class GremlinService {

    @Cacheable(value = "edges")
    public String getEdgeId(long fromId, long toId, String label) {
        // basically finds an edge in graph database
    }


    public Edge createEdge(Vertex from, Vertex to, String label){
        String edgeId = getEdgeId((Long) from.id(), (Long) to.id(), label);
        if (!Util.isEmpty(edgeId)) {
            // if edge created before, use its id to query it again
            return getEdgeById(edgeId);
        } else {
            return createNewEdge((Long) from.id(), (Long) to.id(), label);
        }
    }
}

我没有任何其他的 redis 或缓存配置。虽然它不会抛出任何错误,但它不会缓存任何东西。我用redis-cli检查。

【问题讨论】:

  • 嗨,您能否更新一下您在代码中如何/在何处调用 getEdgeId(...) 方法的问题?
  • 你好,我已经更新了
  • 谢谢。正如古斯塔沃帕西尼所写。这是因为您从同一个班级调用它。将缓存的方法移动到另一个类。

标签: spring-boot spring-data-redis spring-cache


【解决方案1】:

为了使缓存工作,必须从外部类调用要缓存的函数。 这是因为 Spring 为您的 bean 创建了一个代理,并在方法调用通过该代理时解析缓存。 如果函数调用是在内部完成的,它不会传递代理,因此不会应用缓存。

这是解决这个问题的另一个答案:Spring cache @Cacheable method ignored when called from within the same class

【讨论】:

    猜你喜欢
    • 2012-03-03
    • 2021-03-25
    • 2017-06-20
    • 1970-01-01
    • 1970-01-01
    • 2011-04-04
    • 2015-08-10
    • 2014-12-20
    • 1970-01-01
    相关资源
    最近更新 更多