无论是mysql数据库、redis数据库、activeMq,我们都需要创建客户端连接、根据业务逻辑进行增删改查、关闭客户端连接等操作。在Spring中为例简化这一系列的操作。提供了模板类。

将数据访问中的固定和变化部分分开,将相同的数据访问流程固话到模板类中,变化的部分通过回调接口开放出来,用于具体定义数据访问和结果返回的操作,同时保证模板类是线程安全的,以便多个数据访问线程共享同一个模板实例。

在S平日那个中有很多模板类,比如HibernateTemplate、JdbcTemplate、RedisTemplate等等。本文将以RedisTemplate、JdbcTemplate为例,讲解创建连接、执行操作、释放连接这一系列操作;

一、RedisTemplate

对于单个使用线程池的jedis操作步骤请看java操作redis的章节,对于spring整合redis也请看前面章节。本章主要讲解源码!

List<String> list=new ArrayList<String>();
list.add("value1");
list.add("value2");
ListOperations<String, String> listOperations=redisTemplate.opsForList();
listOperations.rightPushAll("listCol", list);

上面的代码是一段向队列中添加List的操作。我们以此为例讲解:

1)首先涉及到的类有:

DefaultListOperation //主要用于封装对List的操作,主要是调用RedisTemplate中的execute方法

StringRedisSerializer //key的序列化和反序列化的工具类

JdkSerializationRedisSerializer //value的序列化和反序列化的工具类

RedisCallback //回调接口,具体定义数据访问和结果返回的操作

RedisTemplate //redis操作模板类,用于封装redis的操作数据流程

RedisConnectionUtils //用于管理redis客户端连接

TransactionSynchronizationManager //线程同步管理

JedisConnectionFactory //创建Jedis的工厂类

Jedis //redis的客户端连接对象

JedisConnection //用于封装真正的Jedis连接对象

2)分析上面代码的源码

redisTemplate.opsForList();//会创建DefaultListOperation 对象,该对象中封装了RedisTemplate。

listOperations.rightPushAll("listCol", list);//具体方法代码如下图

/*****
**DefaultListOperation类中主要的调用
***主要成员变量:RedisTemplate
******/
@Override
public Long rightPushAll(K key, Collection<V> values) {//序列化对象key、value
//调用RedisTemplate的keySerializer、valueSerializer的serialize()
final byte[] rawKey = rawKey(key);
final byte[][] rawValues = rawValues(values);//调用RedisTemplate的方法execute,实现对Redis操作
return execute(new RedisCallback<Long>(){ //实现回调接口public Long doInRedis(RedisConnection connection) {return connection.rPush(rawKey, rawValues);}}, true); //参数exposeConnection(公开连接):true
}@SuppressWarnings("unchecked")
byte[] rawKey(Object key) {Assert.notNull(key, "non null key required");if (keySerializer() == null && key instanceof byte[]) {return (byte[]) key;}//实际调用RedisTemplate来序列化keyreturn keySerializer().serialize(key);
}//调用RedisTemplate的方法
RedisSerializer keySerializer() {return template.getKeySerializer();
}//调用RedisTemplate的方法
<T> T execute(RedisCallback<T> callback, boolean b) {return template.execute(callback, b);
}/*****
**RedisTemplate类中主要的调用
***主要成员变量:JedisConnectionFactory
******/
public <T> T execute(RedisCallback<T> action, boolean exposeConnection, boolean pipeline) {//redis连接工厂,用于创建、关闭redis连接RedisConnectionFactory factory = getConnectionFactory();//内部封装真正的redis连接,用于实现各种操作RedisConnection conn = null;try {//默认不启动事务,redis连接是通过RedisConnectionUtils获得的if (enableTransactionSupport) {// only bind resources in case of potential transaction synchronizationconn = RedisConnectionUtils.bindConnection(factory, enableTransactionSupport);} else {conn = RedisConnectionUtils.getConnection(factory);}//是否和当事务同步管理器程绑定boolean existingConnection = TransactionSynchronizationManager.hasResource(factory);//RedisConnection connToUse = preProcessConnection(conn, existingConnection);//管道状态:用于批量操作boolean pipelineStatus = connToUse.isPipelined();if (pipeline && !pipelineStatus) {connToUse.openPipeline();}//是否为jedisConnection,创建动态代理对象(jdk动态代理技术)RedisConnection connToExpose = (exposeConnection ? connToUse : createRedisConnectionProxy(connToUse));//调用回调函数,执行数据库操作,之部分是动态的,可以由用户自己指定操作T result = action.doInRedis(connToExpose);// close pipelineif (pipeline && !pipelineStatus) {connToUse.closePipeline();}// TODO: any other connection processing?return postProce***esult(result, connToUse, existingConnection);} finally {//非事务操作,释放连接if (!enableTransactionSupport) {RedisConnectionUtils.releaseConnection(conn, factory);}}
}

转载于:https://blog.51cto.com/wlan2014/1899047

Spring-RedisTemplate原理相关推荐

  1. 浅谈:Spring Boot原理分析,切换内置web服务器,SpringBoot监听项目(使用springboot-admin),将springboot的项目打成war包

    浅谈:Spring Boot原理分析(更多细节解释在代码注释中) 通过@EnableAutoConfiguration注解加载Springboot内置的自动初始化类(加载什么类是配置在spring.f ...

  2. spring ioc原理分析

    spring ioc原理分析 spring ioc 的概念 简单工厂方法 spirng ioc实现原理 spring ioc的概念 ioc: 控制反转 将对象的创建由spring管理.比如,我们以前用 ...

  3. Spring MVC 原理探秘 - 一个请求的旅行过程

    1.简介 在前面的文章中,我较为详细的分析了 Spring IOC 和 AOP 部分的源码,并写成了文章.为了让我的 Spring 源码分析系列文章更为丰富一些,所以从本篇文章开始,我将来向大家介绍一 ...

  4. spring aop原理_Spring知识点总结!已整理成142页离线文档(源码笔记+思维导图)...

    写在前面 由于Spring家族的东西很多,一次性写完也不太现实.所以这一次先更新Spring[最核心]的知识点:AOP和IOC 无论是入门还是面试,理解AOP和IOC都是非常重要的.在面试的时候,我没 ...

  5. (转)spring源码解析,spring工作原理

    转自:https://www.ibm.com/developerworks/cn/java/j-lo-spring-principle/ Spring 的骨骼架构 Spring 总共有十几个组件,但是 ...

  6. 不同类的方法 事务问题_深入理解 Spring 事务原理

    Spring事务的基本原理 Spring事务的本质其实就是数据库对事务的支持,没有数据库的事务支持,spring是无法提供事务功能的.对于纯JDBC操作数据库,想要用到事务,可以按照以下步骤进行: 获 ...

  7. spring解耦原理

    spring解耦原理 普通java代码实现功能 class Zhang{void doSome(){Xing xi=new Xing();Xi.doSome();XXX x = new XXX();x ...

  8. Spring MVC 原理探秘 - 容器的创建过程

    1.简介 在上一篇文章中,我向大家介绍了 Spring MVC 是如何处理 HTTP 请求的.Spring MVC 可对外提供服务时,说明其已经处于了就绪状态.再次之前,Spring MVC 需要进行 ...

  9. Spring核心技术原理-(1)-通过Web开发演进过程了解一下为什么要有Spring?

    一.知史可以明鉴 我们学习技术的时代赶上了最好的时代,跳过了很多前人经常踩的坑,前人在踩坑的过程中总结了很多经验和教训,而新时代的我们只是继承了前人的经验和教训,而忽略了这些采坑的过程,以至于我们面对 ...

  10. modelandview使用过程_面试问烂的 Spring AOP 原理、Spring MVC 过程

    点击上方 Java后端,选择 设为星标 优质文章,及时送达 作者:莫那一鲁道链接:www.jianshu.com/p/e18fd44964eb Spring AOP ,SpringMVC ,这两个应该 ...

最新文章

  1. CodeForces - 755C PolandBall and Forest (并查集)
  2. 【手写系列】写一个迷你版的Tomcat
  3. Linux debian 11上安装 Google Chrome浏览器教程
  4. PyQt5 QTableView 全部item居中
  5. linux dd 进度条,Progress 进度条 – DDProgressHUD
  6. MySQL 本可以用Workbench,为什么还要Navicat
  7. js img转换base64
  8. matlab数据显示格式,如何使用MATLAB以图形格式记录和显示数据
  9. lacp静态和动态区别_静态人脸识别和动态人脸识别有哪些区别
  10. Shell:dos新建sh脚本在linux下执行报错“/bin/sh^M”
  11. 二、安装Robot framework-selenium2library
  12. JAVA实现出题团队
  13. 如何在Excel中少犯二(I)
  14. 8.12 腾讯大战360 2133
  15. [渝粤教育] 兴义民族师范学院 数据结构 参考 资料
  16. 整理了46个python人工智能库,详细介绍(含资源),建议收藏
  17. django批量修改table_Django 使用 modelformset 组件批量修改表单数据
  18. 利用ELK技术栈收集nginx日志
  19. python黑色背景rbg_PIL图像转换为RGB,保存为纯黑色图像(python)
  20. 心、肝、脾、肺、肾的毒藏在哪,你知道吗?

热门文章

  1. 交换与路由技术课程期末上机测试题目一
  2. Kotlin-如何创建一个好用的协程作用域
  3. halcon的算子清点: Chapter 2-3-4 控制、开发、文件操作
  4. ubuntu18.04下pyaudio的安装
  5. java代码执行mysql语句_三种执行SQL语句的的JAVA代码
  6. 2021-02-27 永磁同步电机 自抗扰控制 PI调节器 矢量控制 SVPWM
  7. 2021-05-08 docker  拷贝东西到镜像,和拷贝到宿主机
  8. Python PIL.Image和OpenCV图像格式相互转换
  9. Notepad++ 添加Json格式化插件
  10. 自考计算机应用技术实践考核,自考《计算机应用技术》实践环节指导