本文測試環境: Spring Boot 2.1.4.RELEASE + Redis 5.0.4 + CentOS 7
自帶緩存
如果沒有使用緩存中間件,Spring Boot 會使用默認的緩存,我們只需啟用即可
在啟動類添加 @EnableCaching 注解
@SpringBootApplication
@EnableCaching
public class CacheredisApplication {
public static void main(String[] args) {
SpringApplication.run(CacheredisApplication.class, args);
}
}
緩存配置
- @Cacheable: 先判斷有沒有緩存,有緩存取緩存,否則執行后續操作后結果存入緩存
- @CachePut: 操作后結果存入緩存
- @CacheEvict: 清除緩存
具體使用見下面示例:
@Service
//@CacheConfig(cacheNames = "user") // 如果使用該注解, 方法中則可以省略 cacheNames 配置
public class UserServiceImpl implements UserService {
@Autowired
UserDao userDao;
@Override
// 緩存的最終 key 值為 user::id
@Cacheable(cacheNames = "user", key = "#id")
public User get(int id) {
return userDao.get(id);
}
@Override
// condition: 執行方法前判斷是否使用注解的功能; unless: 執行方法后,判斷是否使用注解提供的功能
@CachePut(cacheNames = "user", key = "#user.id", condition = "#user.id<10", unless = "#result.status = 1")
public User update(User user) {
return userDao.update(user);
}
@Override
// 默認規則: 只有一個參數則 key 值取該參數, 如果有多個參數則將這些參數拼接起來作為 key
@CacheEvict(cacheNames = "user")
public boolean delete(int id) {
return userDao.delete(id);
}
@Override
// allEntries 清除 cacheNames 下所有 key; beforeInvocation 方法執行前清除
@CacheEvict(cacheNames = "user", allEntries = true, beforeInvocation = true)
public boolean deleteAll() {
return userDao.deleteAll();
}
}
結合 Redis 使用
關於 Redis 基本使用,參考昨天的隨筆 Spring Boot + Redis 初體驗
添加配置
spring:
cache:
type: redis # 設置使用 redis 作為緩存 (此行可以不配置)
redis:
time-to-live: 300s
# key-prefix: key # 不要配置該項
# use-key-prefix: true # 不要配置該項
redis:
host: 192.168.30.101
port: 6379
database: 0
# password: ******
緩存類添加代碼
@Service
public class UserServiceImpl implements UserService {
@Autowired
StringRedisTemplate redisTemplate;
... ...
}
注意事項
要緩存的類要實現 Serializable 接口
存在問題 (坑)
在配置文件配置 key-prefix 和 use-key-prefix 項生成的 key 會有問題:
| key-prefix | 不配置 | key- | key- |
| use-key-prefix | 不配置 | true | false |
| Redis緩存內的key | user::1 | key-1 | 1 |
如上所示,如果配置了 key-prefix 和 use-key-prefix 設置的 cacheNames 會被覆蓋掉,兩個或以上類的對象緩存會有問題
未解決問題
結合 Redis 使用時即使使用自定義 RedisTemplate 改變了 Serializer, 但在實際序列化時仍然使用的是默認的 JdkSerializationRedisSerializer,不知道為什么會這樣 (這應該也是需要緩存的類為什么必須實現 Serializable 接口),還懇請大神指教!
源碼:GitHub
本人 C# 轉 Java 的 newbie, 如果錯誤或不足歡迎指正,謝謝
參考:
