springboot cache small note

Searching to find the tutorials is certainly a thankless job, there is badly written, but also to write good, but in the end one thing and that is not the system. As for the books introduction of a technical authority, we do not know for several years before it can be published, looking at the English official documents crowded, it's a special and an old blood sprayed on to the screen. Then spray, you have to learn ah. Learn to learn ah, ah, I fell into the above cycle. Good old saying, to know the depth of the river, you have to personally lower river fishing in troubled waters. SO, very pure paper describes a small part of the theme of the cache, not much theory, focusing on projects by myself to everyone and an entry-level guide for future viewing.

In order not to waste time to find the answers you suddenly have mixed feelings, recorded thereon. Key to see the last sentence.

Code verification environment: idea.

Scenes

We often need to query by id entity, the situation is not normal cache are: request URL, query the database and return the results. Using the cache: Request URL- query cache - the cache is directly returned, no cache query the database - returns the result.

Step verification

1. New springboot project idea pom file as follows:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example.testcache</groupId>
    <artifactId>democache</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>democache</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

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

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

2. We want to simulate the process needs to query data DAO layer, service layer provides service. Several classes are listed below:
Entity Class Book:

public class Book {
    private String isbn;
    private String title;

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

    public String getIsbn() {
        return isbn;
    }

    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @Override
    public String toString() {
        return "Book{" +
                "isbn='" + isbn + '\'' +
                ", title='" + title + '\'' +
                '}';
    }
}

Query interface BookRepository:

public interface BookRepository {
    Book getByIsbn(String isbn);
}

Interface SimpleBookRepository:

@Component
public class SimpleBookRepository implements BookRepository {

    @Override
    public Book getByIsbn(String isbn) {

        simulateSlowService();
        return new Book(isbn, "Some book");

    }

    private void simulateSlowService() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }
}

The above code at the time of the query to join three-second delay, you can modify it at any time.
After we were ready to do a good job to test the two cases.

No-cache case

As we all know running springboot very simple way to start the class:

@SpringBootApplication
public class DemocacheApplication {

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

@SpringBootApplication comment barabara. Not explained.

Not built test class, we inject bookRepository achieved by way CommandLineRunner interface, remove with a query method.

@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... strings) 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"));

    }
}

Enter the following:

2017-05-27 10:58:55.800 INFO 8233 — [ main] com.example.testcache.AppRunner : …. Fetching books
2017-05-27 10:58:58.806 INFO 8233 — [ main] com.example.testcache.AppRunner : isbn-1234 –>Book{isbn=’isbn-1234’, title=’Some book’}
2017-05-27 10:59:01.809 INFO 8233 — [ main] com.example.testcache.AppRunner : isbn-4567 –>Book{isbn=’isbn-4567’, title=’Some book’}
2017-05-27 10:59:04.812 INFO 8233 — [ main] com.example.testcache.AppRunner : isbn-1234 –>Book{isbn=’isbn-1234’, title=’Some book’}
2017-05-27 10:59:07.813 INFO 8233 — [ main] com.example.testcache.AppRunner : isbn-4567 –>Book{isbn=’isbn-4567’, title=’Some book’}

Output from the log view, retrieving about every 3 seconds.

Enable Cache

Modify Search method SimpleBookRepository.java class:

@Component
public class SimpleBookRepository implements BookRepository {

    @Override
    @Cacheable("books")
    public Book getByIsbn(String isbn) {

        simulateSlowService();
        return new Book(isbn, "Some book");

    }

    private void simulateSlowService() {
        try {
            Thread.sleep(3000L);
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }
}

In addition, also you need to add @EnableCaching comment on startup class:

@SpringBootApplication
@EnableCaching
public class DemocacheApplication {

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

@EnableCaching small talk

@EnableCaching Notes checks for the cache annotations on public methods spring bean, if such comment is found, it will automatically create proxy to intercept method calls and handle caching behavior.
It can be monitored to have our comments very familiar Cacheable, CachePut and CacheEvict and so on.
Spring Boot automatically configure a suitable cache manager, our example does not use the specified cache library such as EHcache, so we are using your own spring-based java.util.concurrent.ConcurrentHashMap implemented Cache Manager (This feature is from Spring3 .1 began offering).

Start the application again we see the results:

2017-05-27 11:28:21.843 INFO 8318 — [ main] com.example.testcache.AppRunner : …. Fetching books
2017-05-27 11:28:24.855 INFO 8318 — [ main] com.example.testcache.AppRunner : isbn-1234 –>Book{isbn=’isbn-1234’, title=’Some book’}
2017-05-27 11:28:27.860 INFO 8318 — [ main] com.example.testcache.AppRunner : isbn-4567 –>Book{isbn=’isbn-4567’, title=’Some book’}
2017-05-27 11:28:27.861 INFO 8318 — [ main] com.example.testcache.AppRunner : isbn-1234 –>Book{isbn=’isbn-1234’, title=’Some book’}
2017-05-27 11:28:27.861 INFO 8318 — [ main] com.example.testcache.AppRunner : isbn-4567 –>Book{isbn=’isbn-4567’, title=’Some book’}
2017-05-27 11:28:27.862 INFO 8318 — [ main] com.example.testcache.AppRunner : isbn-1234 –>Book{isbn=’isbn-1234’, title=’Some book’}
2017-05-27 11:28:27.862 INFO 8318 — [ main] com.example.testcache.AppRunner : isbn-1234 –>Book{isbn=’isbn-1234’, title=’Some book’}

You will find, as long as the requesting entity has visited, will return results immediately from the cache.

Published 22 original articles · won praise 9 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_19408473/article/details/72779919