4

I am just starting to learn Spring Boot and am trying to use cache with the Google Sheets API to study Springboot. To use cache with Google Sheets in Spring Boot, I added the spring-boot-starter-cache dependency in my pom.xml file and enabled cache support by using the @EnableCaching annotation in my application's main class. I then used the @Cacheable annotation for caching the response from the Google Sheets API when calling a method to get a spreadsheet. However, the cache does not work, as the method is still being called every time.

Here is an example of the code I am using:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class GoogleSheetsService {

    private static final Logger logger = LoggerFactory.getLogger(GoogleSheetsService.class);

    @Cacheable(value = "spreadsheet", key = "#spreadsheetId")
    public Spreadsheet getSpreadsheet(String spreadsheetId) {
        logger.info("Getting spreadsheet from API for {}", spreadsheetId);
        // Call Google Sheets API to get spreadsheet
        return spreadsheet;
    }
}

I expected the cache to return the cached value for the same spreadsheetId, but the method is being called every time and the "Getting spreadsheet from API for {}" log is being printed. Can you please help me understand what might be causing the cache to not work as expected?

1
  • Are you injecting GoogleSheetsService or manually constructing it? Because since caching is taken care of by spring using aspects, the service needs to be injected (using either constructor injection or Autowired annotation) for it to work. Commented Jan 8, 2023 at 22:30

1 Answer 1

1

I can doubt two things.

  1. Are other methods of Google Sheets Service calling the spreadsheet method?

@Cacheable uses the AOP concept of Spring Framework. So it doesn't apply to calling other methods in the same class.

  1. Have you registered the spreadsheet with CacheManager?

With Java Config, it is as follows,

@Configuration
@EnableCaching
public class CacheConfig {

  @Bean
  public CacheManager cacheManager() {
    ConcurrentMapCacheManager mgr = new ConcurrentMapCacheManager();
    mgr.setCacheNames(asList("employees"));
    return mgr;
  }
}

link

Is the spreadsheet registered with cacheManager?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.