SpringBoot-使用缓存

前言

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

spring cache 注解介绍

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

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>

配置文件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

实体类

主键采用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() {
    }
}

Repository接口

继承jpa接口JpaRepository。

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

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

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

@SpringBootApplication
@EnableCaching
public class SpringbootCacheApplication {

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

创建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() {
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中整合Ehcache缓存,需要进行以下几个步骤: 1. 添加Ehcache依赖 在pom.xml文件中添加Ehcache依赖: ``` <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>${ehcache.version}</version> </dependency> ``` 2. 配置Ehcache缓存 在application.yml(或application.properties)文件中配置Ehcache缓存: ``` spring: cache: type: ehcache ehcache: config: classpath:ehcache.xml ``` 其中,`spring.cache.type`属性指定使用缓存类型为Ehcache,`ehcache.config`属性指定Ehcache配置文件的路径(在classpath下)。 3. 编写Ehcache配置文件 在classpath下创建`ehcache.xml`文件,配置Ehcache缓存的相关信息: ``` <ehcache> <diskStore path="java.io.tmpdir"/> <defaultCache maxEntriesLocalHeap="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" diskSpoolBufferSizeMB="30" maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" transactionalMode="off"> </defaultCache> <cache name="userCache" maxEntriesLocalHeap="1000" maxEntriesLocalDisk="10000" eternal="false" diskSpoolBufferSizeMB="20" timeToIdleSeconds="300" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU" transactionalMode="off"> </cache> </ehcache> ``` 其中,`defaultCache`为默认缓存配置,`cache`为自定义缓存配置。 4. 在代码中使用缓存 在需要使用缓存的方法上添加`@Cacheable`注解,指定缓存名称和缓存key: ``` @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override @Cacheable(value = "userCache", key = "#id") public User getUserById(Integer id) { return userDao.getUserById(id); } // ... } ``` 其中,`value`属性指定缓存名称,`key`属性为缓存key表达式,可以使用Spring表达式语言(SpEL)进行动态表达。 以上就是在Spring Boot中整合Ehcache缓存的步骤,通过使用Ehcache缓存可以有效地提高应用程序的性能和响应速度。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值