Cory
Cory

Reputation: 929

Spring cache does not cache anything

I'm using spring-boot-starter-parent version 2.0.1

these are the 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

This is the main class.

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

This's the java method that I want to cache result of it.

@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);
        }
    }
}

I don't have any other configuration for redis or cache. Although it does not throw any error, it does not cache anything. I check with redis-cli.

Upvotes: 1

Views: 2796

Answers (1)

Gustavo Passini
Gustavo Passini

Reputation: 2668

In order for the caching to work, the function to be cached must be called from an external class. That's because Spring creates a proxy for your bean and resolves the caching when the method call passes through that proxy. If the function call is done internally, it doesn't pass the proxy and thus the caching is not applied.

Here's another answer that adresses this question: Spring cache @Cacheable method ignored when called from within the same class

Upvotes: 5

Related Questions