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>
    
  • 相关阅读:
    Python 用SMTP发送邮件
    Python 用IMAP接收邮件
    E-mail Composition and Decoding
    用Python实现gmail邮箱服务,实现两个邮箱之间的绑定(中)
    【日志】-2013.10.31
    21本计算机数学相关的免费电子书【转】
    WordPress搭建Personal Blog【转】
    一句话点亮你的人生
    【日志】-2013.10.28
    转载-smarty教程(基本语法)
  • 原文地址:https://www.cnblogs.com/zhangbin1989/p/9719453.html
Copyright © 2011-2022 走看看