28-SpringBoot——核心-数据缓存Cache

来源:互联网 发布:手机视频录播软件 编辑:程序博客网 时间:2024/06/06 14:11

SpringBoot——核心-数据缓存Cache


【博文目录>>>】


【项目源码>>>】


Spring 缓存支持


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

Spring 支持的CacheManager


针对不同的缓存技术,需要实现不同的CacheManager, Spring 定义了如下Cache Manager 实现。

这里写图片描述

在我们使用任意一个实现的CacheManager 的时候,需注册实现的CacheManager 的Bean。

声名式缓存注解


Spring 提供了4 注解用来声明级存规则。

这里写图片描述

@Cacheable 、@CachePut 、@CacheEvit 都有value 属性,指定的是要使用的缓存名称: key属性指定的是数据在缓存中的存储的键。

开启声名缓存支持


开启声名式缓存支持十分简单,只需在配置类上使用@EnableCaching 注解即可。

Spring Boot 的支持


在Spring 中使用缓存技术的关键是配置CacheManager,而Spring Boot 为我们自动配置了多个CacheManager 的实现。Spring Boot 的CacheManager 的自动配置放置在org.springframework.boot.autoconfigure.cache 包中。

这里写图片描述

Spring Boot 为我们自动配置了EhCacheCacheConfiguration (使用EhCache )、GenericCacheConfiguration (使用Collection )、GuavaCacheConfiguration (使用Guava )、HazelcastCacheConfiguration (使用Hazelcast )、InfinispanCacheConfiguration (使用Infinispan )、JCacheCacheConfiguration (使用JCache )、NoOpCacheConfiguration (不使用存储)、RedisCacheConfiguration (使用Redis )、SimpleCacheConfiguration (使用ConcurrentMap )。在
不做任何额外配置的情况下,默认使用的是SimpleCacheConfiguration ,即使用ConcurrentMapCacheManager 。Spring Boot 支持以“ spring.cache ”为前缀的属性来配置缓存。

这里写图片描述

在Spring Boot 环境下,使用缓存技术只需在项目中导入相关缓存技术的依赖包,并在配置类使用@EnableCaching 开启缓存支持即可。

切换缓存技术


切换缓存技术除了移入相关依赖、包或者自己置以外,使用方式和实战例子保持一致。下面简要讲解在Spring Boot 下, EhCache 和Guava 作为缓存技术的方式,其余缓存技术也是类似的方式。

EhCache


当我们需要使用EhCache 作为缓存技术的时候,我们只需在pom.xrnl 中添加EhCache 的依赖即可。

<dependency>    <groupId>org.ehcache</groupId><artifactId>ehcache</artifactId></dependency>

EhCache 所需的配置文件ehcache.xml 只需放在类路径下, Spring Boot 会自动扫描。

<?xml version="1.0" encoding="UTF-8"?><ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">    <cache name="people"            maxElementsInMemory="1000"            eternal="false"           timeToIdleSeconds="120"           timeToLiveSeconds="120"           overflowToDisk="false"            memoryStoreEvictionPolicy="LRU"/></ehcache>

Guava


使用Guava 作为级存技术的时候,我们也只均在pom.xml 增加Guava依赖

<dependency>    <groupId>com.google.guava</groupId>    <artifactId>guava</artifactId>    <version>23.0</version></dependency>

Redis


使用 Redis ,只需添加下面的依赖即可

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

代码实现


ehcache.xml

<?xml version="1.0" encoding="UTF-8"?><ehcache>    <cache name="people" maxElementsInMemory="1000"/></ehcache>

data.sql

INSERT INTO person (id, name, age, address) VALUES (1, '王俊超', 25, '合肥');INSERT INTO person (id, name, age, address) VALUES (2, 'xx', 19, '北京');INSERT INTO person (id, name, age, address) VALUES (3, 'yy', 20, '上海');INSERT INTO person (id, name, age, address) VALUES (4, 'zz', 24, '南京');INSERT INTO person (id, name, age, address) VALUES (5, 'aa', 28, '武汉');INSERT INTO person (id, name, age, address) VALUES (6, 'bb', 26, '合肥');

application.properties

spring.datasource.driverClassName=com.mysql.jdbc.Driverspring.datasource.url=jdbc\:mysql\://localhost\:3306/springbootspring.datasource.username=rootspring.datasource.password=123456#1spring.jpa.hibernate.ddl-auto=update#2spring.jpa.show-sql=truespring.jackson.serialization.indent_output=true
package com.example.spring.boot.dao;import com.example.spring.boot.domain.Person;import org.springframework.data.jpa.repository.JpaRepository;/** * Author: 王俊超 * Date: 2017-07-18 08:13 * All Rights Reserved !!! */public interface PersonRepository extends JpaRepository<Person, Long> {}
package com.example.spring.boot.domain;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;/** * Author: 王俊超 * Date: 2017-07-18 08:13 * All Rights Reserved !!! */@Entitypublic class Person {    @Id    @GeneratedValue    private Long id;    private String name;    private Integer age;    private String address;    public Person() {        super();    }    public Person(Long id, String name, Integer age, String address) {        super();        this.id = id;        this.name = name;        this.age = age;        this.address = address;    }    public Long getId() {        return id;    }    public void setId(Long id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Integer getAge() {        return age;    }    public void setAge(Integer age) {        this.age = age;    }    public String getAddress() {        return address;    }    public void setAddress(String address) {        this.address = address;    }}
package com.example.spring.boot.service;import com.example.spring.boot.domain.Person;/** * Author: 王俊超 * Date: 2017-07-18 08:15 * All Rights Reserved !!! */public interface DemoService {    Person save(Person person);    void remove(Long id);    Person findOne(Person person);}
package com.example.spring.boot.service.impl;import com.example.spring.boot.dao.PersonRepository;import com.example.spring.boot.domain.Person;import com.example.spring.boot.service.DemoService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.cache.annotation.CacheEvict;import org.springframework.cache.annotation.CachePut;import org.springframework.cache.annotation.Cacheable;import org.springframework.stereotype.Service;/** * Author: 王俊超 * Date: 2017-07-18 08:16 * All Rights Reserved !!! */@Servicepublic class DemoServiceImpl implements DemoService {    @Autowired    PersonRepository personRepository;    @Override    @CachePut(value = "people", key = "#person.id")    public Person save(Person person) {        Person p = personRepository.save(person);        System.out.println("为id、key为:" + p.getId() + "数据做了缓存");        return p;    }    @Override    @CacheEvict(value = "people")//2    public void remove(Long id) {        System.out.println("删除了id、key为" + id + "的数据缓存");        //这里不做实际删除操作    }    @Override    @Cacheable(value = "people", key = "#person.id")//3    public Person findOne(Person person) {        Person p = personRepository.findOne(person.getId());        System.out.println("为id、key为:" + p.getId() + "数据做了缓存");        return p;    }}
package com.example.spring.boot.web;import com.example.spring.boot.domain.Person;import com.example.spring.boot.service.DemoService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/** * Author: 王俊超 * Date: 2017-07-18 08:17 * All Rights Reserved !!! */@RestControllerpublic class CacheController {    @Autowired    DemoService demoService;    @RequestMapping("/put")    public Person put(Person person) {        return demoService.save(person);    }    @RequestMapping("/able")    public Person cacheable(Person person) {        return demoService.findOne(person);    }    @RequestMapping("/evit")    public String evit(Long id) {        demoService.remove(id);        return "ok";    }}
package com.example.spring.boot;import org.springframework.cache.annotation.EnableCaching;import org.springframework.context.annotation.Configuration;/** * Author: 王俊超 * Date: 2017-07-18 08:12 * All Rights Reserved !!! */@Configuration@EnableCachingpublic class AppConfig {}
package com.example.spring.boot;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;/** * Author: 王俊超 * Date: 2017-07-18 07:43 * All Rights Reserved !!! */@SpringBootApplicationpublic class SampleApplication {    public static void main(String[] args) {        SpringApplication.run(SampleApplication.class, args);    }}
原创粉丝点击