
redis常用來作為快取伺服器。快取的好處是減少伺服器的壓力,資料查詢速度快。解決數據響應慢的問題。
新增快取:只用redis的Hash資料型別加入快取。 (建議學習:Redis視訊教學)
例如:需要在查詢的業務功能中,新增快取
1.首先需要在執行正常的業務邏輯之前(查詢資料庫之前),查詢緩存,如果快取中沒有需要的數據,查詢資料庫
為了防止添加快取出錯,影響正常業務代碼的執行,將新增快取的程式碼放置到try-catch程式碼快中,讓程式自動擷取。
2.完成資料庫的查詢操作,查詢完成之後需要將查詢的資料加入快取。
程式碼:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | @Override
public List<TbContent> findContentByCategoryId(Long categoryId) {
try {
String json = jedisClient.hget(CONTENT_LIST, categoryId + "" );
if (json != null) {
List<TbContent> list = JsonUtils.jsonToList(json, TbContent. class );
return list;
}
} catch (Exception e) {
e.printStackTrace();
}
TbContentExample example = new TbContentExample();
Criteria criteria = example.createCriteria();
criteria.andCategoryIdEqualTo(categoryId);
List<TbContent> list = contentMapper.selectByExampleWithBLOBs(example);
try {
jedisClient.hset(CONTENT_LIST, categoryId + "" , JsonUtils.objectToJson(list));
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
|
登入後複製
Json轉換的工具類別:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | package nyist.e3.utils;
import java.util.List;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUtils {
private static final ObjectMapper MAPPER = new ObjectMapper();
public static String objectToJson(Object data) {
try {
String string = MAPPER.writeValueAsString(data);
return string;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
try {
T t = MAPPER.readValue(jsonData, beanType);
return t;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List. class , beanType);
try {
List<T> list = MAPPER.readValue(jsonData, javaType);
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
|
登入後複製
以上是redis怎麼做緩存的詳細內容。更多資訊請關注PHP中文網其他相關文章!