义齿
2535 ワード
最近mysqlテーブルのデータをredisにキャッシュする必要があり、リストにはクエリーにページングする必要があることが示されています.最初はHASH構造が満足できると思っていたが、その後ネットで調べ、ZSETとHASH構造を利用してデータを記憶すればredisページングを実現できる.
手順は次のとおりです.
コードは次のとおりです.
本文はブログの1文の多発プラットフォームOpenWriteから発表します!
手順は次のとおりです.
1. ZSET A id value , ZSET score ;
2. A HASH ,id HASH key;
3. redis zRangeByScore ZSET id , HASH 。
コードは次のとおりです.
/**
* hash
* @param key
* @param hkey
* @param value
* @return
*/
public static boolean hput(String key, String hkey, Object value) {
try {
redisTemplate.opsForHash().put(key, hkey, value);
log.debug("hput {} = {}", key+hkey, value);
return true;
} catch (Exception e) {
log.warn("hput {} = {}", key+hkey, value, e);
}
return false;
}
/**
*
* @param key hash key
* @param hkey hash hkey
* @param score
* @param value
* @return
*/
public static boolean setPage(String key, String hkey, double score, String value){
boolean result = false;
try {
redisTemplate.opsForZSet().add(key+":page", hkey, score);
result = hput(key, hkey, value);
log.debug("setPage {}", key);
} catch (Exception e) {
log.warn("setPage {}", key, e);
}
return result;
}
/**
* hash hkey
* @param key
* @param offset
* @param count
* @return
*/
public static Set getPage(String key, int offset, int count){
Set result = null;
try {
result = redisTemplate.opsForZSet().rangeByScore(key+":page", 1, 100000, (offset-1)*count, count);//1 100000 score , 1-100000
log.debug("getPage {}", key);
} catch (Exception e) {
log.warn("getPage {}", key, e);
}
return result;
}
/**
* key
* @param key
* @return
*/
public static Integer getSize(String key){
Integer num = 0;
try {
Long size = redisTemplate.opsForZSet().zCard(key+":page");
log.debug("getSize {}", key);
return size.intValue();
} catch (Exception e) {
log.warn("getSize {}", key, e);
}
return num;
}
本文はブログの1文の多発プラットフォームOpenWriteから発表します!