redis常本用來(lái)作為緩存服務(wù)器。緩存的好處是減少服務(wù)器的壓力,數(shù)據(jù)查詢速度快。解決數(shù)據(jù)響應(yīng)慢的問(wèn)題。
添加緩存:只用redis的Hash數(shù)據(jù)類型添加緩存。 (推薦學(xué)習(xí):Redis視頻教程)
例如:需要在查詢的業(yè)務(wù)功能中,添加緩存
1.首先需要在執(zhí)行正常的業(yè)務(wù)邏輯之前(查詢數(shù)據(jù)庫(kù)之前),查詢緩存,如果緩存中沒(méi)有需要的數(shù)據(jù),查詢數(shù)據(jù)庫(kù)
為了防止添加緩存出錯(cuò),影響正常業(yè)務(wù)代碼的執(zhí)行,將添加緩存的代碼放置到try-catch代碼快中,讓程序自動(dòng)捕獲。
2.完成數(shù)據(jù)庫(kù)的查詢操作,查詢完成之后需要將查詢的數(shù)據(jù)添加到緩存中。
代碼:
@Override public List<TbContent> findContentByCategoryId(Long categoryId) { // 查詢出的內(nèi)容列表可以添加到緩存中,便于展示,為了保證添加緩存出現(xiàn)錯(cuò)誤不影響程序的正常業(yè)務(wù)功能,可以使用try catch的方式加緩存 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); // 使用selectByExampleWithBLOBs方法會(huì)將content屬性框中的內(nèi)容也查詢出來(lái) List<TbContent> list = contentMapper.selectByExampleWithBLOBs(example); // 操作完成后需要將查詢的內(nèi)容添加到緩存中,因?yàn)樘砑泳彺娴倪^(guò)程可能出錯(cuò),所以使用try catch將異常拋出即可 // categoryId+""將Long類型的數(shù)據(jù)轉(zhuǎn)換成String類型的 try { jedisClient.hset(CONTENT_LIST, categoryId + "", JsonUtils.objectToJson(list)); } catch (Exception e) { e.printStackTrace(); } return list; }
Json轉(zhuǎn)換的工具類:
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; /** * 淘淘商城自定義響應(yīng)結(jié)構(gòu) */ public class JsonUtils { // 定義jackson對(duì)象 private static final ObjectMapper MAPPER = new ObjectMapper(); /** * 將對(duì)象轉(zhuǎn)換成json字符串。 * <p>Title: pojoToJson</p> * <p>Description: </p> * @param data * @return */ public static String objectToJson(Object data) { try { String string = MAPPER.writeValueAsString(data); return string; } catch (JsonProcessingException e) { e.printStackTrace(); } return null; } /** * 將json結(jié)果集轉(zhuǎn)化為對(duì)象 * * @param jsonData json數(shù)據(jù) * @param clazz 對(duì)象中的object類型 * @return */ 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; } /** * 將json數(shù)據(jù)轉(zhuǎn)換成pojo對(duì)象list * <p>Title: jsonToList</p> * <p>Description: </p> * @param jsonData * @param beanType * @return */ 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; } }