注:对缓存支持的使用是在 spring-data-jpa实现了对User用户表的一些操作的基础上进行的。
准备工作(通用):
- 添加依赖:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
-
application.properties
文件中新增spring.jpa.properties.hibernate.show_sql=true
,开启hibernate对sql语句的打印。
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
#每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。
spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop
spring.jpa.properties.hibernate.show_sql=true
- 创建 User 实体(User.java):
@Entity
public class User implements Serializable {
@Id
@GeneratedValue
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private Integer age;
public User() {}
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; }
}
- 单元测试内容:
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTestApplicationTests {
@Autowired
private UserRepository userRepository;
//注入cacheManager,使用debug模式运行单元测试,
//观察cacheManager中的缓存集users以及其中的User对象的缓存加深理解。
@Autowired
private CacheManager cacheManager;
@Before
public void before() { userRepository.save(new User("AAA", 10)); }
@Test
public void contextLoads() throws Exception {
User u1 = userRepository.findByName("AAA");
System.out.println("第一次查询:" + u1.getAge());
User u2 = userRepository.findByName("AAA");
System.out.println("第二次查询:" + u2.getAge());
u1.setAge(20);
userRepository.save(u1);
User u3 = userRepository.findByName("AAA");
System.out.println("第三次查询:" + u3.getAge());
}
}
- 在SpringBoot 主类中增加
@EnableCaching
注解开启缓存功能:
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
1.EnCache的使用:
-
pom.xml
引入cache依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
- 在数据访问接口中,增加缓存配置注解(UserRepository.java):
@CacheConfig(cacheNames = "users")
public interface UserRepository extends JpaRepository<User, Long> {
@Cacheable
User findByName(String name);
//@CachePut(key = "#p0.name")
@Cacheable
User save(User user);
}
2.Redis做集中式缓存
-
pom.xml
引入cache依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
-
application.properties
中增加redis配置,以本地运行为例:
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
Spring Boot会在侦测到存在Redis的依赖并且Redis的配置是可用的情况下,使用RedisCacheManager
初始化CacheManager
。
- 在数据访问接口中增加缓存配置注解:在更新age的时候,通过
@CachePut
来让数据更新操作同步到缓存中(原因:Redis的缓存独立存在于Spring应用之外,对数据库中数据做了更新操作之后,没有通知Redis去更新相应的内容,因此我们取到了缓存中未修改的数据,导致了数据库与缓存中数据的不一致。使用Encache不需要做上述操作,因为EhCache是进程内的缓存框架)
@CacheConfig(cacheNames = "users")
public interface UserRepository extends JpaRepository<User, Long> {
@Cacheable(key = "#p0") // key为缓存对象存储在Map集合中的key值
User findByName(String name);
@CachePut(key = "#p0.name")
User save(User user);
}
Cache注解详解:
-
@CacheConfig
:主要用于配置该类中会用到的一些共用的缓存配置。在这里@CacheConfig(cacheNames = "users")
:配置了该数据访问对象中返回的内容将存储于名为users的缓存对象中,我们也可以不使用该注解,直接通过@Cacheable自己配置缓存集的名字来定义。 -
@Cacheable
:配置了findByName函数的返回值将被加入缓存。同时在查询时,会先从缓存中获取,若不存在才再发起对数据库的访问。该注解主要有下面几个参数:-
value
、cacheNames
:两个等同的参数(cacheNames
为Spring 4新增,作为value
的别名),用于指定缓存存储的集合名。由于Spring 4中新增了@CacheConfig
,因此在Spring 3中原本必须有的value
属性,也成为非必需项了 key
:缓存对象存储在Map集合中的key值,非必需,缺省按照函数的所有参数组合作为key值,若自己配置需使用SpEL表达式,比如:@Cacheable(key = "#p0")
:使用函数第一个参数作为缓存的key值,更多关于SpEL表达式的详细内容可参考官方文档-
condition
:缓存对象的条件,非必需,也需使用SpEL表达式,只有满足表达式条件的内容才会被缓存,比如:@Cacheable(key = "#p0", condition = "#p0.length() < 3")
,表示只有当第一个参数的长度小于3的时候才会被缓存,若做此配置上面的AAA用户就不会被缓存,读者可自行实验尝试。 -
unless
:另外一个缓存条件参数,非必需,需使用SpEL表达式。它不同于condition
参数的地方在于它的判断时机,该条件是在函数被调用之后才做判断的,所以它可以通过对result进行判断。 -
keyGenerator
:用于指定key生成器,非必需。若需要指定一个自定义的key生成器,我们需要去实现org.springframework.cache.interceptor.KeyGenerator
接口,并使用该参数来指定。需要注意的是:该参数与key
是互斥的 -
cacheManager
:用于指定使用哪个缓存管理器,非必需。只有当有多个时才需要使用 -
cacheResolver
:用于指定使用那个缓存解析器,非必需。需通过org.springframework.cache.interceptor.CacheResolver
接口来实现自己的缓存解析器,并用该参数指定。
-
-
@CachePut
:配置于函数上,能够根据参数定义条件来进行缓存,它与@Cacheable
不同的是,它每次都会真实调用函数,所以主要用于数据新增和修改操作上。它的参数与@Cacheable
类似,具体功能可参考上面对@Cacheable参数的解析。 -
@CacheEvict
:配置于函数上,通常用在删除方法上,用来从缓存中移除相应数据。除了同@Cacheable
一样的参数之外,它还有下面两个参数:-
allEntries
:非必需,默认为false。当为true时,会移除所有数据 -
beforeInvocation
:非必需,默认为false,会在调用方法之后移除数据。当为true时,会在调用方法之前移除数据。
-