當咱們平常開發的時候,總會遇到一些緩存問題,說白了就是把項目中一些數據量較大且輕易不改動的數據放入緩存,以便後續請求能夠迅速響應。所以咱們能夠使用redis做爲緩存中間件,我認爲使用redis也仍是從倆個方面考慮:性能和併發。而後就是ace-cache基於spring boot上的註解緩存,自帶輕量級緩存管理頁面,比spring cache更輕量的緩存,支持單個緩存設置過時時間,能夠根據前綴移除緩存。採用fastjson序列化與反序列化,以json串存於緩存之中,ace-cache能夠快速用於平常的spring boot應用之中。java
而後我記錄下在項目中該如何啓動緩存:git
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
<dependency> <groupId>com.github.wxiaoqi</groupId> <artifactId>ace-cache</artifactId> <version>0.0.2</version> </dependency>
配置redis數據源,application.yml文件:github
#redis-cache 相關 redis: pool: maxActive: 300 maxIdle: 100 maxWait: 1000 host: 127.0.0.1 port: 6379 password: timeout: 2000 # 服務或應用名 sysName: ace enable: true database: 0
3.開啓緩存redis
開啓AOP掃描:spring
@EnableAceCache
在Service上進行@Cache註解或@CacheClear註解json
@Override @Cacheable(value = "dataDictCache", key = "'petstore:dataDict:all'") public List<DataDict> getAll() { return dataDictMapper.selectAll(); }
4.註解說明數組
(1)配置緩存@cache緩存
註解參數 | 類型 | 說明 |
---|---|---|
key | 字符串 | 緩存表達式,動態運算出key |
expires | ××× | 緩存時長,單位:分鐘 |
desc | 描述 | 緩存說明 |
parser | Class<? extends ICacheResultParser> | 緩存返回結果自定義處理類 |
generator | Class<? extends IKeyGenerator> | 緩存鍵值自定義生成類 |
(2)清除緩存@cacheclear併發
註解參數 | 類型 | 說明 |
---|---|---|
pre | 字符串 | 清除某些前綴key緩存 |
key | 字符串 | 清除某個key緩存 |
keys | 字符串數組 | 清除某些前綴key緩存 |
generator | Class<? extends IKeyGenerator> | 緩存鍵值自定義生成類 |
(3)默認key動態表達式說明
app
表達式舉例 | 說明 | 舉例 |
---|---|---|
@Cache(key="user:{1}") public User getUserByAccount(String account) |
{1}表示獲取第一個參數值 {2}表示獲取第二個參數值 ……依此類推 |
若:account = ace,則:key = user:ace |
@CacheClear(pre="user{1.account}") User saveOrUpdate(User user) |
{1}表示獲取第一個參數值 {1.xx}表示獲取第一個參數中的xxx屬性 |
若:account=ace,則:key = user:ace |