美文网首页
SpringBoot 使用缓存

SpringBoot 使用缓存

作者: 月弦 | 来源:发表于2019-08-06 12:01 被阅读0次

前言

大多数情况下,我们都会使用数据库。当我们使用的数据频率很好时,就会考虑使用缓存提高响应速度和承载能力。本文来介绍SpringBoot来简单整合缓存,使用SpringBoot+JPA+mysql来进行数据库操作。整合JPA的文章,具体可以参考 SpringBoot 整合JPA

spring cache 注解介绍

  • @Cacheable
    这个注解在执行前先查看缓存中是不是已经存在了,如果存在,直接返回。如果不存在,将方法的返回值放入缓存。
属性 类型 功能
value String[] 缓存的名称 和cacheNames功能一样
cacheNames String[] 缓存的名称和value功能一样
key String 缓存key的值、默认是以所有的参数作为key、也可以直接配置keyGenerator
keyGenerator String 缓存key的生成器
cacheManager String 配置使用那个缓存管理器、和cacheResolver排斥
cacheResolver String 定义使用那个拦截器、和cacheManager互斥
condition String 根据spel表达式来可以配置什么条件下进行缓存 默认全部缓存
unless String 和condition相反
sync boolean 是否开启同步功能、默认不开启
  • @CachePut
    这个注解直接将返回值放入缓存中,通常用于保存和修改方法中
属性 类型 功能
value String[] 缓存的名称 和cacheNames功能一样
cacheNames String[] 缓存的名称和value功能一样
key String 缓存key的值、默认是以所有的参数作为key、也可以直接配置keyGenerator
keyGenerator String 缓存key的生成器
cacheManager String 配置使用那个缓存管理器、和cacheResolver排斥
cacheResolver String 定义使用那个拦截器、和cacheManager互斥
condition String 根据spel表达式来可以配置什么条件下进行缓存 默认全部缓存
unless String 和condition相反
  • @CacheEvict
    这个注解在执行方法执行成功后会从缓存中移除
属性 类型 功能
value String[] 缓存的名称 和cacheNames功能一样
cacheNames String[] 缓存的名称和value功能一样
key String 缓存key的值、默认是以所有的参数作为key、也可以直接配置keyGenerator
keyGenerator String 缓存key的生成器
cacheManager String 配置使用那个缓存管理器、和cacheResolver排斥
cacheResolver String 定义使用那个拦截器、和cacheManager互斥
condition String 根据spel表达式来可以配置什么条件下进行缓存 默认全部缓存
allEntries boolean 是否删除所有键的缓存 默认不删除
beforeInvocation boolean 是否在调用此方法前 删除缓存
  • @CacheConfig
    在类级别统一的配置缓存公共配置.
属性 类型 功能
cacheNames String[] 缓存的名称和value功能一样
keyGenerator String缓存key的生成器
cacheManager String 配置使用那个缓存管理器、和cacheResolver排斥
cacheResolver String 定义使用那个拦截器、和cacheManager互斥
  • @EnableCaching
    开启缓存以及缓存的全局配置
属性 类型 功能
proxyTargetClass boolean 是否要基于cglib生成代理去实现缓存
mode AdviceMode配置那种模式去实现缓存、默认是AdviceMode.PROXY 可以切换为 AdviceMode#ASPECTJ
order int 设置缓存管理器执行的顺序
  • @Caching
    对多个缓存组的配置
属性 类型 功能
cacheable Cacheable 配置获取缓存相关的配置
put CachePut 配置如何更新缓存的相关配置
evict CacheEvict 配置如何删除缓存的相关配置

1、pom.xml文件

<?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>

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

    <groupId>com.huzh</groupId>
    <artifactId>springboot-cache</artifactId>
    <version>1.0-SNAPSHOT</version>

    <name>springboot-cache</name>
    <description>springboot-cache</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!--cache-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <!--jpa-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </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、配置文件application.yml

spring:
  #数据库配置
  datasource:
    url: jdbc:mysql://localhost:3306/test?serverTimezone=GMT
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver

  ##validate  加载hibernate时,验证创建数据库表结构
  ##create   每次加载hibernate,重新创建数据库表结构,这就是导致数据库表数据丢失的原因。
  ##create-drop        加载hibernate时创建,退出是删除表结构
  ##update                 加载hibernate自动更新数据库结构
  ##validate 启动时验证表的结构,不会创建表
  ##none  启动时不做任何操作
  #jpa配置
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

#端口号
server:
  port: 8080

3、实体类

主键采用int型自增。

@Entity
public class House {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    @Column(length = 10)
    private String houseName;
    private String houseSize;

    public int getId() {
        return id;
    }

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

    public String getHouseName() {
        return houseName;
    }

    public void setHouseName(String houseName) {
        this.houseName = houseName;
    }

    public String getHouseSize() {
        return houseSize;
    }

    public void setHouseSize(String houseSize) {
        this.houseSize = houseSize;
    }

    public House(String houseName, String houseSize) {
        this.houseName = houseName;
        this.houseSize = houseSize;
    }

    public House(int id, String houseName, String houseSize) {
        this.id = id;
        this.houseName = houseName;
        this.houseSize = houseSize;
    }

    public House() {
    }
}

4、Repository接口

继承jpa接口JpaRepository。

public interface HouseRepository extends JpaRepository<House, Integer> {
}

5、启动类上加入@EnableCaching开启缓存

@EnableCaching开启缓存以及缓存的全局配置

@SpringBootApplication
@EnableCaching
public class SpringbootCacheApplication {

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

6、创建controller类

访问时观察控制台sql打印情况。

@RestController
public class HouseController {

    @Autowired
    private HouseRepository houseRepository;

    //http://localhost:8080/saveHouse?id=1&houseName=别墅&houseSize=1220平方米
    @GetMapping("/saveHouse")
    @CachePut(value = "house", key = "#id")
    public House saveHouse(Integer id, String houseName, String houseSize) {
        House house = new House(id, houseName, houseSize);
        houseRepository.save(house);
        return house;
    }

    //http://localhost:8080/queryHouse?id=1
    @GetMapping("/queryHouse")
    @Cacheable(value = "house", key = "#id")
    public House queryHouse(Integer id) {
        House house = houseRepository.getOne(id);
        return house;
    }

    //http://localhost:8080/deleteHouse?id=1
    @GetMapping("/deleteHouse")
    @CacheEvict(value = "house", key = "#id")
    public String deleteHouse(Integer id) {
        houseRepository.deleteById(id);
        return "success";
    }

    //http://localhost:8080/deleteCache
    @GetMapping("/deleteCache")
    @CacheEvict(value = "house", allEntries = true)
    public void deleteCache() {
    }
}

相关文章

  • springBoot高级

    springBoot高级 普通缓存 1、在springBoot中可以使用注解式开发缓存,默认没有开启缓存中间件,那...

  • springboot与缓存

    问题一:使用缓存步骤 问题二:常用的缓存注解介绍 问题三:springboot与redis springboot要...

  • SpringBoot 使用 Redis 做缓存

    springboot 使用 redis 做缓存 maven 添加 redis 缓存支持