Skip to content

Commit ee556c1

Browse files
author
alafighting
committed
支持更多注解;实现日志的持久化;完善案例demo;其他优化
1 parent 9391fb2 commit ee556c1

35 files changed

+535
-371
lines changed
Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,24 @@
11
package com.im4j.kakacache.rxjava.demo;
22

3-
import com.im4j.kakacache.rxjava.netcache.CACHE;
3+
import com.im4j.kakacache.rxjava.CACHE;
44
import com.im4j.kakacache.rxjava.netcache.ResultData;
5+
import com.im4j.kakacache.rxjava.netcache.strategy.CacheAndRemoteStrategy;
56

67
import java.util.List;
78

89
import retrofit2.http.GET;
910
import retrofit2.http.Path;
10-
import retrofit2.http.Query;
1111

1212
/**
1313
* @version alafighting 2016-07
1414
*/
1515
public interface GitHubService {
1616

1717
@GET("users/{user}/repos")
18-
@CACHE("cache_key_listRepos")
19-
rx.Observable<ResultData<List<GithubRepoEntity>>> listRepos(@Path("user") String user,
20-
@Query("q") String q);
18+
rx.Observable<List<GithubRepoEntity>> listReposForNormal(@Path("user") String user);
19+
20+
@GET("users/{user}/repos")
21+
@CACHE(value = "custom_key_listRepos", strategy = CacheAndRemoteStrategy.class)
22+
rx.Observable<ResultData<List<GithubRepoEntity>>> listReposForKaka(@Path("user") String user);
2123

2224
}
Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,23 @@
11
package com.im4j.kakacache.rxjava.demo;
22

3-
import com.google.gson.annotations.SerializedName;
3+
import com.im4j.kakacache.rxjava.common.utils.MemorySizeOf;
4+
5+
import java.io.Serializable;
46

57
/**
68
* @version alafighting 2016-07
79
*/
8-
public class GithubRepoEntity {
10+
public class GithubRepoEntity implements MemorySizeOf.SizeOf, Serializable {
911

1012
private String id;
1113
private String name;
12-
@SerializedName("full_name")
13-
private String fullName;
1414
private String description;
1515

1616
public GithubRepoEntity() {
1717
}
18-
public GithubRepoEntity(String id, String name, String fullName, String description) {
18+
public GithubRepoEntity(String id, String name, String description) {
1919
this.id = id;
2020
this.name = name;
21-
this.fullName = fullName;
2221
this.description = description;
2322
}
2423

@@ -27,7 +26,6 @@ public String toString() {
2726
return "GithubRepoEntity{" +
2827
"id='" + id + '\'' +
2928
", name='" + name + '\'' +
30-
", fullName='" + fullName + '\'' +
3129
", description='" + description + '\'' +
3230
'}';
3331
}
@@ -48,19 +46,18 @@ public void setName(String name) {
4846
this.name = name;
4947
}
5048

51-
public String getFullName() {
52-
return fullName;
53-
}
54-
55-
public void setFullName(String fullName) {
56-
this.fullName = fullName;
57-
}
58-
5949
public String getDescription() {
6050
return description;
6151
}
6252

6353
public void setDescription(String description) {
6454
this.description = description;
6555
}
56+
57+
@Override
58+
public long sizeOf() {
59+
return MemorySizeOf.sizeOf(id)
60+
+ MemorySizeOf.sizeOf(name)
61+
+ MemorySizeOf.sizeOf(description);
62+
}
6663
}

app/src/main/java/com/im4j/kakacache/rxjava/demo/MainActivity.java

Lines changed: 29 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -3,28 +3,26 @@
33
import android.os.Bundle;
44
import android.support.annotation.Nullable;
55
import android.support.v7.app.AppCompatActivity;
6-
import android.util.Log;
76
import android.widget.Button;
87

8+
import com.im4j.kakacache.rxjava.KakaCache;
99
import com.im4j.kakacache.rxjava.common.utils.LogUtils;
10-
import com.im4j.kakacache.rxjava.netcache.KakaCache;
1110
import com.im4j.kakacache.rxjava.netcache.retrofit.KakaRxCallAdapterFactory;
12-
import com.im4j.kakacache.rxjava.netcache.strategy.CacheAndRemoteStrategy;
13-
14-
import java.util.concurrent.TimeUnit;
11+
import com.im4j.kakacache.rxjava.netcache.strategy.FirstCacheStrategy;
1512

1613
import retrofit2.Retrofit;
1714
import retrofit2.converter.gson.GsonConverterFactory;
18-
import rx.Observable;
19-
import rx.Subscriber;
2015
import rx.schedulers.Schedulers;
2116

2217
/**
2318
* Demo主界面
2419
* @version alafighting 2016-06
2520
*/
2621
public class MainActivity extends AppCompatActivity {
27-
static final String KEY_CACHE = "key_cache";
22+
static final String KEY_CACHE = "key_cache_listRepos";
23+
24+
private Retrofit retrofit;
25+
private GitHubService service;
2826

2927
private Button btnTestCache;
3028
private Button btnTestRetrofit;
@@ -34,54 +32,42 @@ protected void onCreate(@Nullable Bundle savedInstanceState) {
3432
super.onCreate(savedInstanceState);
3533
setContentView(R.layout.actiity_main);
3634

35+
LogUtils.DEBUG = false;
36+
KakaCache.init(this);
37+
38+
retrofit = new Retrofit.Builder()
39+
.baseUrl("https://api.github.com/")
40+
.addConverterFactory(GsonConverterFactory.create(KakaCache.gson().create()))
41+
.addCallAdapterFactory(KakaRxCallAdapterFactory.create())
42+
.build();
43+
44+
service = retrofit.create(GitHubService.class);
45+
3746
btnTestCache = (Button) findViewById(R.id.btn_test_cache);
3847
btnTestCache.setOnClickListener(view -> {
39-
remote().compose(KakaCache.transformer(KEY_CACHE, new CacheAndRemoteStrategy())).subscribe(data -> {
40-
Log.e("main", "next data=" + data);
48+
// 不修改原有代码,增加对Cache的支持
49+
service.listReposForNormal("alafighting")
50+
.compose(KakaCache.transformer(KEY_CACHE, new FirstCacheStrategy()))
51+
.subscribe(data -> {
52+
LogUtils.log("next data=" + data);
4153
}, error -> {
42-
Log.e("main", "error", error);
54+
LogUtils.log("error", error);
4355
}, () -> {
44-
Log.e("main", "completed");
56+
LogUtils.log("completed");
4557
});
4658
});
4759

4860
btnTestRetrofit = (Button) findViewById(R.id.btn_test_retrofit);
4961
btnTestRetrofit.setOnClickListener(view -> {
50-
Retrofit retrofit = new Retrofit.Builder()
51-
.baseUrl("https://api.github.com/")
52-
.addConverterFactory(GsonConverterFactory.create(KakaCache.gson().create()))
53-
.addCallAdapterFactory(KakaRxCallAdapterFactory.create())
54-
.build();
55-
56-
GitHubService service = retrofit.create(GitHubService.class);
57-
58-
// // 不修改原有代码,增加对Cache的支持
59-
// service.listRepos("octocat").compose(KakaCache.transformer(KEY_CACHE, new FirstCacheStrategy())).subscribeOn(Schedulers.io()).subscribe(data -> {
60-
// LogUtils.e(data);
61-
// }, error -> {
62-
// LogUtils.e(error);
63-
// });
64-
6562
// 通过注解,自动支持Cache
66-
service.listRepos("octocat", "abc")
63+
service.listReposForKaka("alafighting")
6764
.subscribeOn(Schedulers.io())
6865
.subscribe(data -> {
69-
LogUtils.e(data);
70-
}, error -> {
71-
LogUtils.e(error);
72-
});
66+
LogUtils.log("listReposForKaka => "+data);
67+
}, error -> {
68+
LogUtils.log(error);
69+
});
7370
});
7471
}
7572

76-
private rx.Observable<String> remote() {
77-
return Observable.create(new Observable.OnSubscribe<String>() {
78-
@Override
79-
public void call(Subscriber<? super String> subscriber) {
80-
Log.e("main", "loadRemote");
81-
subscriber.onNext("test remote");
82-
subscriber.onCompleted();
83-
}
84-
}).delay(3, TimeUnit.SECONDS);
85-
}
86-
8773
}

library/libs/lite-orm-1.9.1.jar

122 KB
Binary file not shown.
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.im4j.kakacache.rxjava;
2+
3+
import com.im4j.kakacache.rxjava.netcache.strategy.CacheStrategy;
4+
import com.im4j.kakacache.rxjava.netcache.strategy.FirstCacheStrategy;
5+
6+
import java.lang.annotation.Documented;
7+
import java.lang.annotation.Retention;
8+
import java.lang.annotation.Target;
9+
10+
import static java.lang.annotation.ElementType.METHOD;
11+
import static java.lang.annotation.RetentionPolicy.RUNTIME;
12+
13+
@Documented
14+
@Target(METHOD)
15+
@Retention(RUNTIME)
16+
public @interface CACHE {
17+
18+
/**
19+
* 缓存的KEY
20+
* @return 空表示由系统自动生成
21+
*/
22+
String value() default "";
23+
24+
/**
25+
* 是否启用缓存
26+
* @return 默认启用
27+
*/
28+
boolean enable() default true;
29+
30+
/**
31+
* 缓存策略
32+
* @return
33+
*/
34+
Class<? extends CacheStrategy> strategy() default FirstCacheStrategy.class;
35+
36+
}

library/src/main/java/com/im4j/kakacache/rxjava/netcache/KakaCache.java renamed to library/src/main/java/com/im4j/kakacache/rxjava/KakaCache.java

Lines changed: 38 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
1-
package com.im4j.kakacache.rxjava.netcache;
1+
package com.im4j.kakacache.rxjava;
22

3-
4-
import android.os.Environment;
5-
import android.util.Log;
3+
import android.content.Context;
64

75
import com.google.gson.GsonBuilder;
86
import com.google.gson.JsonDeserializationContext;
@@ -11,19 +9,23 @@
119
import com.google.gson.JsonParseException;
1210
import com.google.gson.JsonSerializationContext;
1311
import com.google.gson.JsonSerializer;
14-
import com.im4j.kakacache.rxjava.common.utils.TypeToken;
12+
import com.im4j.kakacache.rxjava.common.utils.LogUtils;
13+
import com.im4j.kakacache.rxjava.common.utils.Utils;
1514
import com.im4j.kakacache.rxjava.core.CacheCore;
16-
import com.im4j.kakacache.rxjava.core.CacheTarget;
1715
import com.im4j.kakacache.rxjava.core.disk.converter.SerializableDiskConverter;
1816
import com.im4j.kakacache.rxjava.core.disk.journal.LRUDiskJournal;
1917
import com.im4j.kakacache.rxjava.core.disk.storage.FileDiskStorage;
2018
import com.im4j.kakacache.rxjava.core.memory.journal.LRUMemoryJournal;
2119
import com.im4j.kakacache.rxjava.core.memory.storage.SimpleMemoryStorage;
2220
import com.im4j.kakacache.rxjava.manager.RxCacheManager;
21+
import com.im4j.kakacache.rxjava.netcache.ResultData;
2322
import com.im4j.kakacache.rxjava.netcache.strategy.CacheStrategy;
23+
import com.litesuits.orm.LiteOrm;
2424

2525
import java.io.File;
26+
import java.lang.reflect.ParameterizedType;
2627
import java.lang.reflect.Type;
28+
import java.util.Arrays;
2729

2830
import rx.Observable;
2931

@@ -36,13 +38,28 @@ public final class KakaCache {
3638
private KakaCache() {
3739
}
3840

41+
// 缓存默认有效期
42+
private static final int DEFAULT_EXPIRES = 12 * 60 * 60 * 1000;
43+
// 缓存保存路径
44+
private static final String DEFAULT_STORAGE_DIR = "kakacache";
45+
46+
private static LiteOrm liteOrm;
3947
private static RxCacheManager cacheManager;
40-
private static int expires = 12 * 60 * 60 * 1000;
48+
private static Context context;
49+
50+
public static void init(Context context) {
51+
KakaCache.context = context.getApplicationContext();
52+
}
53+
54+
public static RxCacheManager manager() {
55+
if (liteOrm == null) {
56+
liteOrm = LiteOrm.newSingleInstance(context, "cache_journal.db");
57+
}
58+
liteOrm.setDebugged(true); // open the log
4159

42-
private static RxCacheManager getCacheManager() {
4360
if (cacheManager == null) {
44-
File storageDir = new File(Environment.getExternalStorageDirectory(), "aaa_test");
45-
Log.e("RxRemoteCache", "storageDir="+storageDir.getAbsolutePath());
61+
File storageDir = new File(Utils.getStorageCacheDir(context), DEFAULT_STORAGE_DIR);
62+
LogUtils.log("storageDir="+storageDir.getAbsolutePath());
4663

4764
storageDir.mkdirs();
4865

@@ -51,27 +68,15 @@ private static RxCacheManager getCacheManager() {
5168
coreBuilder.memoryJournal(new LRUMemoryJournal());
5269
coreBuilder.memoryMax(10 * 1024 * 1024, 1000);
5370
coreBuilder.disk(new FileDiskStorage(storageDir));
54-
coreBuilder.diskJournal(new LRUDiskJournal());
71+
coreBuilder.diskJournal(new LRUDiskJournal(liteOrm));
5572
coreBuilder.diskMax(30 * 1024 * 1024, 10 * 1000);
5673
coreBuilder.diskConverter(new SerializableDiskConverter());
5774
CacheCore core = coreBuilder.create();
58-
cacheManager = new RxCacheManager(core);
75+
cacheManager = new RxCacheManager(core, DEFAULT_EXPIRES);
5976
}
6077
return cacheManager;
6178
}
6279

63-
public static <T> rx.Observable<T> load(String key) {
64-
return getCacheManager().load(key);
65-
}
66-
67-
public static <T> rx.Observable<Boolean> save(String key, T value, CacheTarget target) {
68-
return getCacheManager().save(key, value, expires, target);
69-
}
70-
71-
public static <T> rx.Observable<Boolean> save(String key, T value) {
72-
return save(key, value, CacheTarget.MemoryAndDisk);
73-
}
74-
7580

7681

7782
public static <T> Observable.Transformer<T, ResultData<T>> transformer(String key, CacheStrategy strategy) {
@@ -87,9 +92,9 @@ public static GsonBuilder gson() {
8792

8893
private static class CacheTransformer<T> implements Observable.Transformer<T, ResultData<T>> {
8994
private String key;
90-
private CacheStrategy<T> strategy;
95+
private CacheStrategy strategy;
9196

92-
public CacheTransformer(String key, CacheStrategy<T> strategy) {
97+
public CacheTransformer(String key, CacheStrategy strategy) {
9398
this.key = key;
9499
this.strategy = strategy;
95100
}
@@ -103,11 +108,16 @@ private static class ResultDataAdapter<T> implements JsonSerializer<ResultData<T
103108
@Override
104109
public ResultData<T> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
105110
throws JsonParseException {
106-
return new ResultData(null, null, context.deserialize(json, new TypeToken<T>(){}.getType()));
111+
return new ResultData(null, null, context.deserialize(json, getWrapType(typeOfT)));
107112
}
108113
@Override
109114
public JsonElement serialize(ResultData<T> src, Type typeOfSrc, JsonSerializationContext context) {
110-
return context.serialize(src.data, new TypeToken<T>(){}.getType());
115+
return context.serialize(src.data, getWrapType(typeOfSrc));
116+
}
117+
118+
private static Type getWrapType(Type typeOf) {
119+
ParameterizedType type = (ParameterizedType) typeOf;
120+
return Arrays.asList(type.getActualTypeArguments()).get(0);
111121
}
112122
}
113123

0 commit comments

Comments
 (0)