70 springboot 声明式缓存 spring cache

声明式缓存
spring 定义 CacheManager 和Cache 接口用来统一不同的缓存技术。例如JCache,Ehcache,Hazelcast,Guava,Redis 等。在使用Spring集成Cache时候,需要注册实现的CacheManager 的Bean。

Springboot 为我们自动配置了JcachecCacheConfiguration,EhCacheConfiguration,HazelcastCacheConfiguration,GuavaCacheConfiguration,RedisCacheConfiguration,SimpleCacheConfiguration等

默认适应ConcurrenMapCacheManager
在我们不使用其他第三方花奴才能依赖的时候,springoot自动采用ConcurrenMapCacheManager作为缓存管理器。
环境依赖
在pom文件中引入spring-boot-starter-cache环境依赖:

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

创建一个Car数据访问层
先创建一个实体类

package com.taotao.xuexi1.entity;

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

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

    public String getIsbn() {
       return isbn;
    }

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

    public String getTitle() {
        return title;
    }

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


2,创建一个数据库访问接口

package com.taotao.xuexi1.service;

import com.taotao.xuexi1.entity.Car;

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


这个可以写一个很复杂的数据查询操作,比如曹志勇mysql,这里只是做了一个线程的延迟操作。当做数据库查询的时间
实现接口类:

package com.taotao.xuexi1.service.impl;


import com.taotao.xuexi1.entity.Car;
import com.taotao.xuexi1.service.BookRepository;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

@Component
public class SimpleBookRepository implements BookRepository {
    @Override
    public Car getByIsbn(String isbn) {
        simulateSlowService();
        return new Car(isbn,"Some book");
    }


    private void simulateSlowService() {
        try {
             long time=6000L;
             Thread.sleep(time);
        }catch (Exception e){
            e.getMessage();
        }
    }
}



测试类

package com.taotao.xuexi1.config;

import com.taotao.xuexi1.service.BookRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;


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

    }
}

最后启动程序,你会发现程序一次3s内打印一行日志。这时候还没有开启缓存技术。


开启缓存技术
在程序接口中加入@EnableCaching 开启缓存技术。

package com.taotao.xuexi1;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;


@EnableCaching
@SpringBootApplication
public class Xuexi1Application {

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

}

在需要缓存的地方加入@Cacheable注解,比如在getByIsbn() 方法加入@Cacheable("books"),这个方法开启了缓存策略,当缓存有这个数据的时候,会直接出数据,不会去等待查询数据库。


package com.taotao.xuexi1.service.impl;


import com.taotao.xuexi1.entity.Car;
import com.taotao.xuexi1.service.BookRepository;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

@Component
public class SimpleBookRepository implements BookRepository {
    @Override
   @Cacheable("books")
    public Car getByIsbn(String isbn) {
        simulateSlowService();
        return new Car(isbn,"Some book");
    }


    private void simulateSlowService() {
        try {
             long time=6000L;
             Thread.sleep(time);
        }catch (Exception e){
            e.getMessage();
        }
    }
}





©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 《小王子》这本书,作者说,是写给大人的童话故事。语言通俗简练,故事极简单,但是深藏人生的哲理。 爱究竟是什么?那些...
    雪花迟舞阅读 1,476评论 0 12
  • 讲师:芳芳 整理人:玲玲 关于感冒发烧的这个定义呢,大家可以去百度百科里面去查哈,我这里就不过度的去讲了,因为有...
    阳光森林_玲玲阅读 1,049评论 0 2
  • 在城市呆得越久,受够了各种非自然生长起来的农产品,各种过度加工的食品,各种钢筋水泥的建筑物,人们在日复一日的...
    荷oo阅读 171评论 1 1