您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

redis怎么做缓存

2026/2/17 4:24:44发布10次查看
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怎么做缓存的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product