Spring Boot Part 13: Springboot integrates spring cache

This article describes how to use the default spring cache in springboot,

Declarative Caching

Spring defines the CacheManager and Cache interfaces to unify different caching technologies. For example JCache, EhCache, Hazelcast, Guava, Redis, etc. When using Spring to integrate Cache, we need to register the implemented CacheManager Bean.

Spring Boot automatically configures JcacheCacheConfiguration, EhCacheCacheConfiguration, HazelcastCacheConfiguration, GuavaCacheConfiguration, RedisCacheConfiguration, SimpleCacheConfiguration, etc. for us.

Use ConcurrenMapCacheManager by default

When we do not use other third-party cache dependencies, springboot automatically uses ConcurrenMapCacheManager as the cache manager.

environment dependent

Introduce the spring-boot-starter-cache environment dependency in the pom file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

Create a book data access layer

First create an entity class

 public class Book {

    private String isbn;
    private String title;

    public Book(String isbn, String title) {
        this.isbn = isbn;
        this.title = title;
    }
  ....getter
  ....setter  

 }

Create a data provider

public interface BookRepository {

    Book getByIsbn(String isbn);

}

This you can write a very complex data query operation, such as operating mysql, nosql and so on. In order to demonstrate this chestnut, I only do a delay operation of the thread, which is regarded as the time to query the database.

Implement the interface class:

@Component
public class SimpleBookRepository implements BookRepository {

    @Override

    public Book getByIsbn(String isbn) {
        simulateSlowService();
        return new Book(isbn, "Some book");
    }

    // Don't do this at home
    private void simulateSlowService() {
        try {
            long time = 3000L;
            Thread.sleep(time);
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }

}

test class

@Component
public class AppRunner implements CommandLineRunner {

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

    private final BookRepository bookRepository;

    public AppRunner(BookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }

    @Override
    public void run(String... args) throws Exception {
        logger.info(".... Fetching books");
        logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234"));
        logger.info("isbn-4567 -->" + bookRepository.getByIsbn("isbn-4567"));
        logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234"));
        logger.info("isbn-4567 -->" + bookRepository.getByIsbn("isbn-4567"));
        logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234"));
        logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234"));
    }

}

Start the program, and you will find that the program prints in sequence on the console:

2014-06-05 12:15:35.783 … : …. Fetching books

2014-06-05 12:15:40.783 … : isbn-1234 → >Book{isbn=’isbn-1234’, title=’Some book’}

2014-06-05 12:15:43.784 … : isbn-1234 →Book{isbn=’isbn-1234’, title=’Some book’}

2014-06-05 12:15:46.786 … : isbn-1234 →Book{isbn=’isbn-1234’, title=’Some book’}

You will find that the program prints a line of logs in sequence for 3s. At this time, the cache technology has not been turned on.

Enable caching technology

Add @EnableCaching to the entry of the program to enable caching technology:

@SpringBootApplication
@EnableCaching
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Add the @Cacheable annotation where you need to cache, such as adding @Cacheable("books") to the getByIsbn() method, this method enables the caching strategy, when the cache has this data, it will return the data directly without waiting to query the database.

@Component
public class SimpleBookRepository implements BookRepository {

    @Override
    @Cacheable("books")
    public Book getByIsbn(String isbn) {
        simulateSlowService();
        return new Book(isbn, "Some book");
    }

    // Don't do this at home
    private void simulateSlowService() {
        try {
            long time = 3000L;
            Thread.sleep(time);
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }

}

Then start the program again, and you will find that the program prints:

isbn-1234 →Book{isbn=’isbn-1234’, title=’Some book’}
2017-04-23 18:17:09.479 INFO 8054 —- [ main] forezp.AppRunner : isbn-4567 →Book{isbn=’isbn-4567’, title=’Some book’}
2017-04-23 18:17:09.480 INFO 8054 —- [ main] forezp.AppRunner : isbn-1234 →Book{isbn=’isbn-1234’, title=’Some book’}
2017-04-23 18:17:09.480 INFO 8054 —- [ main] forezp.AppRunner : isbn-4567 →Book{isbn=’isbn-4567’, title=’Some book’}
2017-04-23 18:17:09.481 INFO 8054 —- [ main] forezp.AppRunner : isbn-1234 →Book{isbn=’isbn-1234’, title=’Some book’}
2017-04-23 18:17:09.481 INFO 8054 —- [ main] forezp.AppRunner : isbn-1234 →Book{isbn=’isbn-1234’, title=’Some book’}

Only the first 2 data are printed, the program waits for 3s, and the subsequent data is instantly printed on the console, which shows that the cache is working.

Source code download: https://github.com/forezp/SpringBootLearning

References

caching

Spring Boot Secrets and Practice (2) Data Cache Chapter - Quick Start

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324539994&siteId=291194637