Spring Boot系列(十八) 缓存

   Spring定义了org.springframework.cache.CacheManager和org.springframework.cache.Cache接口用来统一不  
同的缓存技术。其中,CacheManager是Spring提供的各种缓存技术抽象接口,Cache接口包含缓存的各种操作(增  
删改查,我们一般不会直接和此接口打交道)。  

   针对不同的缓存技术,是需要实现不同的CacheManager,Spring定义了如下表所示的CacheManager实现:
  • CacheManager描述
    SimpleCacheManager使用简单的Collection来存储缓存,主要用来测试用途
    ConcurrentMapCacheManager使用ConcurrentMap来存储
    NoOpCacheManager仅测试用途,不会市级存储缓存
    EhCacheCacheManager使用EhCache作为缓存技术
    GuavaCacheManager使用Google Guava的GuavaCache作为缓存技术
    HazelcastCacheManager使用Hazelcast作为缓存技术
    JCacheCacheManager支持JCache(JSR-107)标准的实现作为缓存技术,如Apache Commons JCS
    RedisCacheManager使用Redis作为缓存技术

Spring Boot的支持:

    在Spring Boot中使用缓存时,CacheManager是自动配置的,只需要导入相关的缓存技术的依赖包,并在配置  
类上使用@EnableCaching开启缓存技术支持即可。缓存配置如下:
spring.cache.type= #可选generic,ehcache,hazelcast,infinispan,jcache,redis,guava,simple, none
spring.cache.cache-names= #程序启动时创建缓存名称
spring.cache.ehcache.config= #ehcache配置文件地址
spring.cache.hazelcast.config= #hazelcast配置文件地址
spring.cache.infinispan.config= #infinispan配置文件地址
spring.cache.jcache.config= #jcache配置文件地址
spring.cache.jcache.provider= #当多个jcache实现在类路径中的时候,制定jcache实现
spring.cache.guava.spec= #guava spec

下面以Redis为例:

  1. 导入Redis依赖包
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-redis</artifactId>
</dependency>


2. 启动缓存

@SpringBootApplication
@EnableCaching
public class SpringBoot181CacheEhcacheApplication {

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


3. 在接口上使用缓存
Domain:

@Entity
public class User implements Serializable{

    private static final long serialVersionUID = -8971505764090290428L;
    @Id
    @GeneratedValue
    private Integer id;
    private String name;
    private Date birthday;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }
}

Repository:

@CacheConfig(cacheNames = "users")
public interface UserRepository extends JpaRepository<User, Long>{

    @Cacheable(value="user",key="#p0")
    User findByName(String name);

    @SuppressWarnings("unchecked")
    @CachePut(value="user",key="#p0.name")
    User save(User user);
}


4. 测试缓存

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringBoot181CacheEhcacheApplication.class)
public class SpringBoot181CacheEhcacheApplicationTests {

    @Autowired
    private RedisCacheManager cacheManager;

    @Autowired
    private CacheManager cacheManager1;

    @Test
    public void contextLoads() {
    }

    @Autowired
    private UserRepository userRepository;

    /*@Before
    public void before() {
        userRepository.save(new User("AAA", 10));
    }*/

    @Test
    public void test() throws Exception {

        System.out.println(cacheManager);

        System.out.println(cacheManager1);

        User u1 = userRepository.findByName("王传奇");
        System.out.println("第一次查询:" + u1.getBirthday());

        u1.setBirthday(new Date());
        userRepository.save(u1);

        User u2 = userRepository.findByName("王传奇");
        System.out.println("第二次查询:" + u2.getBirthday());
    }
}

通过测试:
(1)在保存user时(使用了@Cacheable),会将数据缓存到user中,查询该记录时,不会发出sql语句
(2)在第一次查询时发出sql语句,将查询结果缓存到user中,第二次查询时不会发出sql语句,而是从缓存中直接读取。

5. 切换EhCache缓存
(1)切换依赖包:

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

(2)配置ehcache.xml,只需要放在类路径下,Spring Boot会自动扫描

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd">
    <cache name="users"
           maxEntriesLocalHeap="200"
           timeToLiveSeconds="600">
    </cache>
</ehcache>


6. 其他

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值