Spring Boot 中使用Cache

cache

缓存经常被使用来提高系统性能和增加系统吞吐量,避免直接访问数据库等其他低速的系统。

@Cacheable 

作用于方法上,主要用来触发缓存的读取操作。如果缓存存在,那么目标方法是不会被调用的,它是直接取缓存中的数据。如果缓存不存在,那么就进入到方法中获取结果同时会缓存起来。一个方法是可以声明多个缓存的。

@Cacheable("user")
public User findUser(User user)
对于不同的缓存实现,缓存的对象(比如上面的User )最好实现序列化 Serializable 接口,这样方便切换到分布式的各个缓存系统。

@Cacheable中有两个重要属性:key 、value。
像上面那样不写明的,默认就是value。上面的写法等同于:

@Cacheable(value="user")
public User findUser(User user)
value 属性是必需要有的,它表示当前方法的返回值会被存在哪个Cache 上,对应的是Cache 的名称。当然前面说过可以同时缓存在多个缓存上。

@Cacheable({"user1","user2"})
public User findUser(User user)
key 属性 用来指定Spring 缓存方法的返回结果所对应的key 。该性属性支持EL表达式的。

@Cacheable(value="findUser" ,key="#user.id")
public User findUser(User user)
这个属性是非必需的,如果没指定该属性时,Spring 会使用默认的策略生成key 。这默认的生成策略是什么样子的呢。
1.如果只有一个参数,那么这个参数就是key ;
2.如果没有参数,那么key 就是 SimpleKey.EMPTY  也就是0作为key;
public static final SimpleKey EMPTY = new SimpleKey( new Object[0]);
3.如果多个参数,那么就用所有参数的SimpleKey作为key ,(SimpleKey 就是某个参数的hashCode)

不过在真实项目中,我们都是要指定这两个参数key 和 value 的,(value 一般直接用方法名,我们做的项目中就是)

@CacheEvict

该注解是使缓存失效(也就是删除缓存或是清空缓存),与@Cacheable 对应,也需要指定key  cacheNames(value)。

@CacheEvict(cacheNames="findUser" ,key="#user.id")
public User deleteUser(User user)
上面的意思就是清空 findUser 这个缓存项中的 键值为"#user.id"的缓存。
不过一般缓存失效都要失效多个,常用Caching 这一个混合注解来失效多个缓存

@Caching(evict={@CacheEvict(cacheNames="findUser" ,key="#user.id"),
                             @CacheEvict(cacheNames="listUser" ,key="#user.id")})
public User deleteUser(User user)

启用缓存


如果使用Spring 自带的缓存管理器,需要在application.properties 中配置属性
spring.cache.type=Simple

如果使用 Spring Cache ,那么需要在pom中添加依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
    <version>2.0.0.RELEASE</version>
</dependency>



最后,在启动类中将缓存功能打开,添加 @EnableCaching 注解
package com.hlm;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

/**
* 启动类,放在此位置能让Spring Boot 扫描整个项目
* @author Administrator
*
*/
@SpringBootApplication
@EnableCaching
public class HlmApplication {

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

    }

}


猜你喜欢

转载自blog.csdn.net/mottohlm/article/details/80782638