文章目录
- 简介
- 引入依赖
- 常用注解
- application.yml
- 使用
- 1. 启动类添加注解
- 使用方法上添加注解
简介
- Spring Cache是一个框架,实现了基于注解的缓存功能
- 底层可以使用EHCache、Caffeine、Redis实现缓存。
注解一般放在Controller的方法上,@CachePut 注解一般有两个参数,第一个时存储的名称,第二个时名称后边的key,使用SpEL动态的计算key。其余的注解也都是这两个参数。在用户端的查询操作需要使用@Cacheable,服务器端的增删改都使用@CacheEvict
引入依赖
SpringCache
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
Redis
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
mysql
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
mybatis
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
常用注解
application.yml
server:
port: 8888
spring:
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
username: root
password: root
redis:
host: localhost
port: 6379
password: 123456
database: 1
# 日志
logging:
level:
com:
itheima:
mapper: debug
service: info
controller: info
使用
1. 启动类添加注解
package com.itheima;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@Slf4j
@SpringBootApplication
-----------------------------------------
添加下面的注解
@EnableCaching
-----------------------------------------
public class CacheDemoApplication {
public static void main(String[] args) {
SpringApplication.run(CacheDemoApplication.class,args);
log.info("项目启动成功...");
}
}