zoukankan      html  css  js  c++  java
  • springboot+缓存

    1、在pom.xml中加入依赖

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

    2、在启动器上开启缓存注解

    @EnableCaching
    

    3、在需要缓存的方法上加注解

    @Cacheable("userList") // 标识读缓存操作
    @CachePut(cacheNames = ["user"], key = "#user.id")// 写入缓存
    @CacheEvict(cacheNames = ["user"], key = "#id")// 根据 key (值为id) 来清除缓存
    @Cacheable(cacheNames = ["user"], key = "#id") // 如果缓存存在,直接读取缓存值; 如果不存在调用目标方法,并将方法返回结果放入缓存
    

    4、缓存类型

    在Spring Boot中通过@EnableCaching注解自动化配置合适的缓存管理器(CacheManager),Spring Boot根据下面的顺序去侦测缓存提供者:

    Generic
    JCache (JSR-107)
    EhCache 2.x
    Hazelcast
    Infinispan
    Redis
    Guava
    Simple
    

    除了按顺序侦测外,我们也可以通过配置属性spring.cache.type来强制指定。我们可以通过debug调试查看cacheManager对象的实例来判断当前使用了什么缓存。

    5、把缓存改成ehcache

    在src/main/resources目录下创建:ehcache.xml

    <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:noNamespaceSchemaLocation="ehcache.xsd">
    
        <cache name="users"
               maxEntriesLocalHeap="200"
               timeToLiveSeconds="600">
        </cache>
    
    </ehcache>
    

    加上依赖包

    <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache</artifactId>
    </dependency>
    
  • 相关阅读:
    Android Activity与Service的交互方式
    Android Service和Thread的区别
    Android Binder机制简单了解
    Android内的生命周期整理
    Android App的生命周期是什么
    ListView item 中TextView 如何获取长按事件
    Go之并发处理(售票问题)
    Go之简单并发
    Go之函数直接实现接口
    Go之类型判断
  • 原文地址:https://www.cnblogs.com/zhangbin1989/p/9719453.html
Copyright © 2011-2022 走看看