点滴积累-redis的使用

2024-08-26 05:32
文章标签 使用 redis 积累 点滴

本文主要是介绍点滴积累-redis的使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

背景

大家都知道oracle是大型数据库,而mysql是中小型数据库。Oracle支持大并发、大访问量,是OLTP(on-line transaction processing)最好的工具。那么为什么规模大且安全性能要求高的阿里还用mysql呢,原因是他们用了一个法宝,redis。

redis的好处

redis实现数据的读写,同时利用对列处理器定时器定时将数据写入mysql大大减轻了数据库的压力。

具体应用

下面简单聊聊redis在项目中的具体使用。

1、在controller中加入redis

1)在web层的Spring-mvc.xml

在我们需要加入redis的controller添加

<property name="jediscluster" ref="jedisCluster"></property>


2)在具体的controller中添加

JedisCluster  jediscluster;public JedisCluster getJediscluster() {return jediscluster;}public void setJediscluster(JedisCluster jediscluster) {this.jediscluster = jediscluster;}

3)存储key,value类型

添加:

	@RequestMapping("test1")public void test1(HttpServletRequest request, HttpServletResponse response) {//添加缓存(String)jediscluster.set("key", "value");
}
删除:

@RequestMapping("test2")publicvoid test2(HttpServletRequest request, HttpServletResponse response) {//根据key删除缓存jediscluster.del("key");}


查询:

@RequestMapping("test3")public void test3(HttpServletRequest request, HttpServletResponse response) {//查询缓存(String)String string = jediscluster.get("key");}

4)存储list

添加:

//添加list
@RequestMapping("test4")
public  void test4(HttpServletRequest request,HttpServletResponse response) throws Exception {
jediscluster.set("listkey" ,JsonUtils.objectToJson(list));	}
删除:

@RequestMapping("test5")
public  void test5(HttpServletRequest request,HttpServletResponse response) throws Exception {
jediscluster.del("listkey");	}
查询:

@RequestMapping("test6")
public  void test6(HttpServletRequest request,HttpServletResponse response) throws Exception {
List<EnrollStudent> enrollStudentList = new ArrayList<EnrollStudent>();//获取缓存String json = jediscluster.get("listkey");//将json转化为list
enrollStudentList = JsonUtils.jsonToList(json,EnrollStudent.class);
}

5)存储实体,添加和删除同list,区别是查询转换,调用jsonToPojo

查询:

@RequestMapping("test6")
public  void test6(HttpServletRequest request,HttpServletResponse response) throws Exception {EnrollStudent enrollStudent= null;     
//获取缓存String json = jediscluster.get("listkey");//将json转化为list
enrollStudent = JsonUtils.jsonToPojo (json,EnrollStudent.class);
}

6)存储List<Map<Serializable,Serializable>>,添加和删除同list,区别是查询转换,调用jsonToListMap

@RequestMapping("test7")public  void test7(HttpServletRequest request,HttpServletResponse response) throws Exception {List<Map<Serializable, Serializable>> listmap=new ArrayList<Map<Serializable, Serializable>>();try {String json=jediscluster.get("listkey ");listmap=JsonUtils.jsonToListMap(json, List.class);} catch (IOException e) {e.printStackTrace();}
}

7)Demo实现:新生入学,存储所有学生信息,分别存储

@RequestMapping("/queryEnrollStudentInfo")public void findStudent(HttpServletRequest request,HttpServletResponse response) throws Exception {// 取得考生号String cEECode = (String) request.getSession().getAttribute("name");		//数据库名称String databaseNames = "itoo_freshmen";// 查数据的List<EnrollStudent> enrollStudentList = new ArrayList<EnrollStudent>();EnrollStudent enrollStudent= null;try {// 从redis中取缓存数据,如果有直接返回缓存中的数据,没有的话查询数据库String studentInfo = jediscluster.get(databaseNames + cEECode);if (!StringUtils.isEmpty(studentInfo)) {enrollStudent = JsonUtils.jsonToPojo(studentInfo,EnrollStudent.class);} else {try {// 根据数据库名称查询所有学生信息enrollStudentList = enrollStudentBean.findAllStudent(databaseNames);//循环遍历,将所有的学号取出来if (enrollStudentList.size() > 0 && enrollStudentList != null) {for (int i = 0; i < enrollStudentList.size(); i++) {EnrollStudent enrollStudentNew = new EnrollStudent();if (enrollStudentList.get(i).getcEECode() != null) {enrollStudentNew.setcEECode(enrollStudentList.get(i).getcEECode().toString());}//添加缓存,key值为databaseNames+学号jediscluster.set(databaseNames+ enrollStudentList.get(i).getcEECode().toString(), JsonUtils.objectToJson(enrollStudentList.get(i)));// 过期时间2hjediscluster.expire(databaseNames+ enrollStudentList.get(i).getcEECode().toString(), 2*3600);		System.out.println(databaseNames+ enrollStudentList.get(i).getcEECode().toString());}// studentInfo = jediscluster.get(databaseNames + cEECode);}} catch (Exception e) {e.printStackTrace();}}} catch (Exception e) {e.printStackTrace();}

2、在service层加入redis:

1)、读取配置文件:

    JedisCluster jediscluster =null;public BuildTypeBeanImpl(){//在执行此实例化的时候就会完成所有注入ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-redis.xml");jediscluster = (JedisCluster)ctx.getBean("jedisCluster");}

2)、具体的存储格式同上

3)、将以上Demo在Service层实现

	/*** 根据考生号查询学生信息-齐伟-2017年2月17日16:37:58* * @throws Exception*/@Overridepublic EnrollStudent findStudentByCEECode(String databaseName,String cEECode) throws Exception {EnrollStudent enrollStudent = new EnrollStudent();// 从redis中取缓存数据,如果有直接返回缓存中的数据,没有的话查询数据库String studentInfo = jediscluster.get(databaseName + cEECode);if (!StringUtils.isEmpty(studentInfo)) {enrollStudent = this.jsonToPojo(studentInfo, EnrollStudent.class);} else {// 根据数据库名称查询所有学生信息List<EnrollStudent> enrollStudentList = enrollStudentEao.findAllStudentByColleageName(databaseName, "");// 循环遍历,将所有的学号取出来if (!enrollStudentList.isEmpty() && enrollStudentList != null) {for (int i = 0; i < enrollStudentList.size(); i++) {// 添加缓存,key值为databaseNames+学号,过期时间2小时jediscluster.set(databaseName+ enrollStudentList.get(i).getCEECode().toString(),this.objectToJson(enrollStudentList.get(i)));// 过期时间2hjediscluster.expire(databaseName + enrollStudentList.get(i), 2 * 3600);}studentInfo = jediscluster.get(databaseName + cEECode);if (!StringUtils.isEmpty(studentInfo)) {enrollStudent = this.jsonToPojo(studentInfo,EnrollStudent.class);}}}return enrollStudent;}

小结

考虑以上两种demo实现,可取后一种,将业务写在service层,有利于代码复用。redis的使用,程序员必备!




      

这篇关于点滴积累-redis的使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1107679

相关文章

深入理解Go语言中二维切片的使用

《深入理解Go语言中二维切片的使用》本文深入讲解了Go语言中二维切片的概念与应用,用于表示矩阵、表格等二维数据结构,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧... 目录引言二维切片的基本概念定义创建二维切片二维切片的操作访问元素修改元素遍历二维切片二维切片的动态调整追加行动态

prometheus如何使用pushgateway监控网路丢包

《prometheus如何使用pushgateway监控网路丢包》:本文主要介绍prometheus如何使用pushgateway监控网路丢包问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录监控网路丢包脚本数据图表总结监控网路丢包脚本[root@gtcq-gt-monitor-prome

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件

SpringBoot线程池配置使用示例详解

《SpringBoot线程池配置使用示例详解》SpringBoot集成@Async注解,支持线程池参数配置(核心数、队列容量、拒绝策略等)及生命周期管理,结合监控与任务装饰器,提升异步处理效率与系统... 目录一、核心特性二、添加依赖三、参数详解四、配置线程池五、应用实践代码说明拒绝策略(Rejected

C++ Log4cpp跨平台日志库的使用小结

《C++Log4cpp跨平台日志库的使用小结》Log4cpp是c++类库,本文详细介绍了C++日志库log4cpp的使用方法,及设置日志输出格式和优先级,具有一定的参考价值,感兴趣的可以了解一下... 目录一、介绍1. log4cpp的日志方式2.设置日志输出的格式3. 设置日志的输出优先级二、Window

Ubuntu如何分配​​未使用的空间

《Ubuntu如何分配​​未使用的空间》Ubuntu磁盘空间不足,实际未分配空间8.2G因LVM卷组名称格式差异(双破折号误写)导致无法扩展,确认正确卷组名后,使用lvextend和resize2fs... 目录1:原因2:操作3:报错5:解决问题:确认卷组名称​6:再次操作7:验证扩展是否成功8:问题已解

Qt使用QSqlDatabase连接MySQL实现增删改查功能

《Qt使用QSqlDatabase连接MySQL实现增删改查功能》这篇文章主要为大家详细介绍了Qt如何使用QSqlDatabase连接MySQL实现增删改查功能,文中的示例代码讲解详细,感兴趣的小伙伴... 目录一、创建数据表二、连接mysql数据库三、封装成一个完整的轻量级 ORM 风格类3.1 表结构