springboot快取
阿新 • • 發佈:2020-12-27
參考文章
springboot快取
1、引用jia包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
2、Spring Boot入口類中加入@EnableCaching註解開啟快取功能
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
3、方法上加入快取
@CacheConfig(cacheNames = "student")
public interface StudentService {
@CachePut(key = "#p0.sno")
Student update(Student student) ;
@CacheEvict(key = "#p0")
void deleteStudentBySno(String sno);
@Cacheable(key = "#p0")
Student queryStudentBySno(String sno);
}
快取註解說明:
@CacheConfig:主要用於配置該類中會用到的一些共用的快取配置。在這裡@CacheConfig(cacheNames = “student”):配置了該資料訪問物件中返回的內容將儲存於名為student的快取物件中,我們也可以不使用該註解,直接通過@Cacheable自己配置快取集的名字來定義;
@Cacheable:配置了queryStudentBySno函式的返回值將被加入快取。同時在查詢時,會先從快取中獲取,若不存在才再發起對資料庫的訪問。該註解主要有下面幾個引數:
- value、cacheNames:兩個等同的引數(cacheNames為Spring
4新增,作為value的別名),用於指定快取儲存的集合名。由於Spring 4中新增了@CacheConfig,因此在Spring
3中原本必須有的value屬性,也成為非必需項了; - key:快取物件儲存在Map集合中的key值,非必需,預設按照函式的所有引數組合作為key值,若自己配置需使用SpEL表示式,比如:@Cacheable(key
= “#p0”):使用函式第一個引數作為快取的key值,更多關於SpEL表示式的詳細內容可參考https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#cache; - condition:快取物件的條件,非必需,也需使用SpEL表示式,只有滿足表示式條件的內容才會被快取,比如:@Cacheable(key
= “#p0”, condition = “#p0.length() < 3”),表示只有當第一個引數的長度小於3的時候才會被快取; - unless:另外一個快取條件引數,非必需,需使用SpEL表示式。它不同於condition引數的地方在於它的判斷時機,該條件是在函式被呼叫之後才做判斷的,所以它可以通過對result進行判斷;
- keyGenerator:用於指定key生成器,非必需。若需要指定一個自定義的key生成器,我們需要去實現org.springframework.cache.interceptor.KeyGenerator介面,並使用該引數來指定;
- cacheManager:用於指定使用哪個快取管理器,非必需。只有當有多個時才需要使用;
- cacheResolver:用於指定使用那個快取解析器,非必需。需通過org.springframework.cache.interceptor.CacheResolver介面來實現自己的快取解析器,並用該引數指定;
@CachePut:清除之前的快取,呼叫方法,把結果重新放入快取。它的引數與@Cacheable類似,具體功能可參考上面對@Cacheable引數的解析;
@CacheEvict:配置於函式上,通常用在刪除方法上,用來從快取中移除相應資料。除了同@Cacheable一樣的引數之外,它還有下面兩個引數:
- allEntries:非必需,預設為false。當為true時,會移除所有資料;
- beforeInvocation:非必需,預設為false,會在呼叫方法之後移除資料。當為true時,會在呼叫方法之前移除資料。
redis
1、在application.yml中配置Redis:
spring:
redis:
# Redis資料庫索引(預設為0)
database: 0
# Redis伺服器地址
host: localhost
# Redis伺服器連線埠
port: 6379
pool:
# 連線池最大連線數(使用負值表示沒有限制)
max-active: 8
# 連線池最大阻塞等待時間(使用負值表示沒有限制)
max-wait: -1
# 連線池中的最大空閒連線
max-idle: 8
# 連線池中的最小空閒連線
min-idle: 0
# 連線超時時間(毫秒)
timeout: 0
2、建立一個Redis配置類
package com.springboot.config;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
// 自定義快取key生成策略
@Bean
@Override
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, java.lang.reflect.Method method, Object... params) {
StringBuffer sb = new StringBuffer();
sb.append(target.getClass().getName()).append(":").append(method.getName());
for (Object obj : params) {
sb.append(":").append(obj.toString());
}
return sb.toString();
}
};
}
// 快取管理器
@Bean
public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
// 設定快取過期時間
cacheManager.setDefaultExpiration(10000);
return cacheManager;
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
setSerializer(template);// 設定序列化工具
template.afterPropertiesSet();
return template;
}
private void setSerializer(StringRedisTemplate template) {
@SuppressWarnings({"rawtypes", "unchecked"})
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
}
}
3、如果要使用自定義的KeyGenerator,@Cacheable 不能使用key
@CacheConfig(cacheNames = "user")
public interface UserService {
@CacheEvict(allEntries = true)
User update(User student);
@CacheEvict(allEntries = true)
void deleteUserBySno(String sno);
@Cacheable
User queryUserBySno(String sno);
}
1、測試
@Test
public void test1() throws Exception {
Student student1 = this.studentService.queryStudentBySno("001");
System.out.println("學號" + student1.getSno() + "的學生姓名為:" + student1.getName());
Student student2 = this.studentService.queryStudentBySno("001");
System.out.println("學號" + student2.getSno() + "的學生姓名為:" + student2.getName());
User user1 = this.userService.queryUserBySno("001");
System.out.println("ID " + user1.getSno() + "的使用者姓名為:" + user1.getName());
User user2 = this.userService.queryUserBySno("001");
System.out.println("ID " + user2.getSno() + "的使用者姓名為:" + user2.getName());
}
執行結果
從資料庫查詢資料 sno :001
學號001的學生姓名為:小紅
學號001的學生姓名為:小紅
從資料庫查詢資料 sno :001
ID 001的使用者姓名為:小明
ID 001的使用者姓名為:小明
第一次查詢走資料庫,第二次查詢走快取,如下圖。紅色的是student,綠色的是user
2、測試
@Test
public void test3() {
User user1 = this.userService.queryUserBySno("001");
System.out.println("Id" + user1.getSno() + "的使用者姓名為:" + user1.getName());
user1 = this.userService.queryUserBySno("001");
System.out.println("Id" + user1.getSno() + "的使用者姓名為:" + user1.getName());
user1.setName("康康");
this.userService.update(user1);
user1 = this.userService.queryUserBySno("001");
System.out.println("Id" + user1.getSno() + "的使用者姓名為:" + user1.getName());
user1 = this.userService.queryUserBySno("001");
System.out.println("Id" + user1.getSno() + "的使用者姓名為:" + user1.getName());
}
執行結果:
從資料庫查詢資料 sno :001
Id001的使用者姓名為:小明
Id001的使用者姓名為:小明
修改資料 :{"name":"康康","sex":"man","sno":"001"}
從資料庫查詢資料 sno :001
Id001的使用者姓名為:小明
Id001的使用者姓名為:小明
第一次查詢走資料庫,第二次走快取,修改後清空快取,第三次走資料庫,第四次走快取