Solon 詳解系列文章:
Solon 框架詳解(一)- 快速入門
Solon 框架詳解(二)- Solon的核心
Solon 框架詳解(三)- Solon的web開發
Solon 框架詳解(四)- Solon的事務傳播機制
Solon 框架詳解(五)- Solon擴展機制之Solon Plugin
Solon 框架詳解(六)- Solon的校驗框架使用、定制與擴展
Solon 框架詳解(七)- Solon Ioc 的注解對比Spring及JSR330
Solon 框架詳解(八)- Solon的緩存框架使用和定制
Solon 框架詳解(九)- 渲染控制之定制統一的接口輸出
Solon 框架詳解(十)- Solon 的常用配置
Solon 框架詳解(十一)- Solon Cloud 的配置說明
solon.data
框加在完成 @Tran 注解的支持同時,還提供了 @Cache、@CachePut、@CacheRemove 注解的支持;可以為業務開發提供良好的便利性
Solon 的緩存注解只支持:Controller 、Service 、Dao 類下的方法。相對於 Spring Boot ,功能類似;但提供了基於 key 和 tags 的兩套管理方案。
- key :相當於緩存的唯一標識,沒有指定時會自動生成(要注意key沖突)
- tags:相當於緩存的索引,可以有多個(用於批量刪除)
(一)示例
從Demo開始,先感受一把
@Controller
public class CacheController {
/**
* 執行結果緩存10秒,使用 key=test_${label} 並添加 test 標簽
* */
@Cache(key="test_${label}", tags = "test" , seconds = 10)
@Mapping("/cache/")
public Object test(int label) {
return new Date();
}
/**
* 執行后,清除 標簽為 test 的所有緩存
* */
@CacheRemove(tags = "test")
@Mapping("/cache/clear")
public String clear() {
return "清除成功(其實無效)-" + new Date();
}
/**
* 執行后,更新 key=test_${label} 的緩存
* */
@CachePut(key = "test_${label}")
@Mapping("/cache/clear2")
public Object clear2(int label) {
return new Date();
}
}
(二)定制分布式緩存
Solon 的緩存標簽,是通過CacheService接口提供支持的。定制起來也相當的方便,比如:對接Memcached...
1. 了解 CacheService 接口:
public interface CacheService {
//保存
void store(String key, Object obj, int seconds);
//獲取
Object get(String key);
//移除
void remove(String key);
}
2. 定制基於 Memcached 緩存服務:
public class MemCacheService implements CacheService{
private MemcachedClient _cache = null;
public MemCacheService(Properties props){
//略...
}
@Override
public void store(String key, Object obj, int seconds) {
if (_cache != null) {
_cache.set(key, seconds, obj);
}
}
@Override
public Object get(String key) {
if (_cache != null) {
return _cache.get(key);
} else {
return null;
}
}
@Override
public void remove(String key) {
if (_cache != null) {
_cache.delete(key);
}
}
}
3. 通過配置換掉默認的緩存服務:
@Configuration
public class Config {
//此緩存,將替代默認的緩存服務
@Bean
public CacheService cache(@Inject("${cache}") Properties props) {
return new MemCacheService(props);
}
}
(三)注解說明
@Cache 注解:
屬性 | 說明 |
---|---|
service() | 緩存服務 |
seconds() | 緩存時間 |
key() | 緩存唯一標識 |
tags() | 緩存標簽,多個以逗號隔開(為當前緩存塊添加標簽,用於清除) |
@CachePut 注解:
屬性 | 說明 |
---|---|
service() | 緩存服務 |
seconds() | 緩存時間 |
key() | 緩存唯一標識 |
tags() | 緩存標簽,多個以逗號隔開(為當前緩存塊添加標簽,用於清除) |
@CacheRemove 注解:
屬性 | 說明 |
---|---|
service() | 緩存服務 |
key() | 緩存唯一標識 |
tags() | 清除緩存標簽,多個以逗號隔開 |
附:Solon項目地址
- gitee: https://gitee.com/noear/solon
- github: https://github.com/noear/solon