【数据库】redis怎么做缓存
2019-11-21数据库搜奇网50°c
A+ A-
redis常本用来作为缓存服务器。缓存的优点是削减服务器的压力,数据查询速度快。处理数据相应慢的题目。
增加缓存:只用redis的Hash数据范例增加缓存。 (引荐进修:Redis视频教程)
比方:须要在查询的营业功用中,增加缓存
1.起首须要在实行一般的营业逻辑之前(查询数据库之前),查询缓存,假如缓存中没有须要的数据,查询数据库
为了防备增加缓存失足,影响一般营业代码的实行,将增加缓存的代码安排到try-catch代码快中,让顺序自动捕捉。
2.完成数据库的查询操纵,查询完成以后须要将查询的数据增加到缓存中。
代码:
@Override public List<TbContent> findContentByCategoryId(Long categoryId) { // 查询出的内容列表能够增加到缓存中,便于展现,为了保证增加缓存涌现毛病不影响顺序的一般营业功用,能够运用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要领会将content属性框中的内容也查询出来 List<TbContent> list = contentMapper.selectByExampleWithBLOBs(example); // 操纵完成后须要将查询的内容增加到缓存中,由于增加缓存的历程能够失足,所以运用try catch将非常抛出即可 // categoryId+""将Long范例的数据转换成String范例的 try { jedisClient.hset(CONTENT_LIST, categoryId + "", JsonUtils.objectToJson(list)); } catch (Exception e) { e.printStackTrace(); } return list; }
Json转换的东西类:
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 { // 定义jackson对象 private static final ObjectMapper MAPPER = new ObjectMapper(); /** * 将对象转换成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效果集转化为对象 * * @param jsonData json数据 * @param clazz 对象中的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数据转换成pojo对象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; } }
以上就是redis怎么做缓存的细致内容,更多请关注ki4网别的相干文章!
标签:redis