文章目录

  • 参考视频
  • 事务回顾
    • 事务的作用
  • 事务管理
    • Spring事务核心对象
      • PlatformTransactionManager
      • TransactionDefinition
      • TransactionStatus
    • 案例环境
    • 编程式事务
    • 声明式事务(XML)
    • 声明式事务(注解)
    • 事务传播行为
  • 模板对象
    • redisTemplate
  • 事务底层原理解析

参考视频

https://www.bilibili.com/video/BV1yq4y1N78E?spm_id_from=333.337.search-card.all.click

事务回顾

事务的作用

  1. 当数据库操作序列中个别操作失败时,提供一个方式使数据库状态恢复到正常状态(A),保障数据库即使在异常状态下任然能够保持数据一致性(C)(要么操作前状态,要么操作后状态)
  2. 当出现并发访问数据库时,在多个访问间进行相互隔离,防止并发访问操作结果互相干扰(I)

事务特征(ACID)

  • 原子性(Atomicity)指事务是一个不可分割的整体,其中的操作要么全执行或全部执行
  • 一致性(Consistency)事务前后数据的完整性必须保持一致
  • 隔离性(Isolation)事务的隔离性是多个用户并发访问数据库时,数据库为每个用户开启的事务,不能被其他事务的操作数据所干扰,多个并发事务之间要相互隔离
  • 持久性(Durability)持久性是指一个事务一旦被提交,他对数据库中的数据的改变就是永久性的,接下来即使数据库发生故障也不应该对其有任何影响


事务管理

Spring事务核心对象

用于解决业务层事务问题

PlatformTransactionManager


TransactionDefinition

TransactionStatus

案例环境

编程式事务

    @Autowiredprivate DataSource dataSource;public void transfer(Integer outId,Integer inId,Double money){//开启事务PlatformTransactionManager ptm = new DataSourceTransactionManager(dataSource);//事务定义TransactionDefinition td = new DefaultTransactionDefinition();//事务状态TransactionStatus ts = ptm.getTransaction(td);//提交事务accountDao.outMoney(outId,money);int i = 1/0;accountDao.inMoney(inId,money);ptm.commit(ts);}


声明式事务(XML)

基于aop的事务控制 spring给出了专门的名称空间

<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/>
</bean><!--定义事务管理的通知类-->
<tx:advice id=“txAdvice” transaction-manager="txManager"><!--定义控制的事务--><tx:attributes><!--全盘读写事务--><tx:method name="*" read-only="false"/> <!--给度的方法指定读事务--><tx:method name="get*" read-only="true"/> <tx:method name="find*" read-only="true"/></tx:attributes>
</tx:advice>
<aop:config><aop:pointcut id="pt" expression="execution(* com.itheima.service.*Service.*(..))"><aop:advisor advice-ref="txAdvice" pointcut-ref="pt" />
</aop:config>


声明式事务(注解)


一般声明式注解是添加在接口上,不会添加在实现类上

事务传播行为



模板对象

  • TransactionTemplate
  • JdbcTemplate
  • RedisTemplate
  • RabbitTemplate
  • JmsTemplate
  • HibernateTemplate
  • RestTemplate

redisTemplate

测试redis是否可连接

<dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>2.9.1</version>
</dependency>
@Test{Jedis jedis = new Jedis(192.168.1.20,6379);jedis.set("name","itheima");jedis.close();
}

需要确保redis服务器设置protected-mode no
cat redis.conf | grep -v "#" | grep -v "^$"

RedisConfig

package com.itheima.config;import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;@PropertySource("redis.properties")
public class RedisConfig {@Value("${redis.host}")private String hostName;@Value("${redis.port}")private Integer port;//    @Value("${redis.password}")
//    private String password;@Value("${redis.maxActive}")private Integer maxActive;@Value("${redis.minIdle}")private Integer minIdle;@Value("${redis.maxIdle}")private Integer maxIdle;@Value("${redis.maxWait}")private Integer maxWait;@Bean//配置RedisTemplatepublic RedisTemplate createRedisTemplate(RedisConnectionFactory redisConnectionFactory){//1.创建对象RedisTemplate redisTemplate = new RedisTemplate();//2.设置连接工厂redisTemplate.setConnectionFactory(redisConnectionFactory);//3.设置redis生成的key的序列化器,对key编码进行处理RedisSerializer stringSerializer = new StringRedisSerializer();redisTemplate.setKeySerializer(stringSerializer);redisTemplate.setHashKeySerializer(stringSerializer);//4.返回return redisTemplate;}@Bean//配置Redis连接工厂public RedisConnectionFactory createRedisConnectionFactory(RedisStandaloneConfiguration redisStandaloneConfiguration,GenericObjectPoolConfig genericObjectPoolConfig){//1.创建配置构建器,它是基于池的思想管理Jedis连接的JedisClientConfiguration.JedisPoolingClientConfigurationBuilder builder = (JedisClientConfiguration.JedisPoolingClientConfigurationBuilder)JedisClientConfiguration.builder();//2.设置池的配置信息对象builder.poolConfig(genericObjectPoolConfig);//3.创建Jedis连接工厂JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisStandaloneConfiguration,builder.build());//4.返回return jedisConnectionFactory;}@Bean//配置spring提供的Redis连接池信息public GenericObjectPoolConfig createGenericObjectPoolConfig(){//1.创建Jedis连接池的配置对象GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();//2.设置连接池信息genericObjectPoolConfig.setMaxTotal(maxActive);genericObjectPoolConfig.setMinIdle(minIdle);genericObjectPoolConfig.setMaxIdle(maxIdle);genericObjectPoolConfig.setMaxWaitMillis(maxWait);//3.返回return genericObjectPoolConfig;}@Bean//配置Redis标准连接配置对象public RedisStandaloneConfiguration createRedisStandaloneConfiguration(){//1.创建Redis服务器配置信息对象RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();//2.设置Redis服务器地址,端口和密码(如果有密码的话)redisStandaloneConfiguration.setHostName(hostName);redisStandaloneConfiguration.setPort(port);
//        redisStandaloneConfiguration.setPassword(RedisPassword.of(password));//3.返回return redisStandaloneConfiguration;}}

redis.properties

# redis服务器主机地址
redis.host=192.168.40.130
#redis服务器主机端口
redis.port=6378#redis服务器登录密码
#redis.password=itheima#最大活动连接
redis.maxActive=20
#最大空间连接
redis.maxIdle=10
#最小空闲连接
redis.minIdle=0
#最大等待时间
redis.maxWait=-1
package com.itheima.service.impl;import com.itheima.domain.Account;
import com.itheima.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
@Service("accountService")
public class AccountServiceImpl implements AccountService {@Autowiredprivate RedisTemplate redisTemplate;public void save(Account account) {}public void changeMoney(Integer id, Double money) {//等同于redis中set account:id:1 100redisTemplate.opsForValue().set("account:id:"+id,money);}public Double findMondyById(Integer id) {//等同于redis中get account:id:1Object money = redisTemplate.opsForValue().get("account:id:" + id);return new Double(money.toString());}
}
//        redisTemplate.type()
//        redisTemplate.persist()
//        redisTemplate.move()
//        redisTemplate.hasKey()
//        redisTemplate.getExpire()
//        redisTemplate.expire()
//        redisTemplate.delete()
//        redisTemplate.rename();
//        数据类型
//        redisTemplate.opsForValue().;
//        redisTemplate.opsForHash().;
//        redisTemplate.opsForList().;
//        redisTemplate.opsForSet().;
//        redisTemplate.opsForZSet();
//
//        阻塞
//        redisTemplate.boundValueOps().;
//        主从
//        redisTemplate.slaveOf();
//        redisTemplate.slaveOfNoOne();
//        集群
//        redisTemplate.opsForCluster()

事务底层原理解析


第四章 ---- 事务RedisTemplate相关推荐

  1. 数据库系统概念总结:第十四章 事务

    周末无事水文章,期末备考的总结资料 第十四章 事务 14.1 事务概念 事务是访问并可能更新各种数据项的一个程序执行单元 ACID特性 –原子性(Atomicity):事务的所有操作都在数据库中正确反 ...

  2. 《深入理解分布式事务》第四章 分布式事务的基本概念和理论知识

    <深入理解分布式事务>第四章 分布式事务的基本概念和理论知识 文章目录 <深入理解分布式事务>第四章 分布式事务的基本概念和理论知识 一.分布式系统架构 1.简介 2.分布式事 ...

  3. mySQL教程 第10章 事务和锁

    第10章 事务和锁 数据库事务(Database Transaction) ,是指作为单个逻辑工作单元执行的一系列操作. 事务处理可以确保除非事务性单元内的所有操作都成功完成,否则不会永久更新面向数据 ...

  4. 第四章-分布式数据库HBase

    第四章-分布式数据库HBase 文章目录 第四章-分布式数据库HBase HBase简介 HBase数据模型 数据模型概念 概念视图 物理视图 面向列的存储 HBase实现原理 HBase功能组件 表 ...

  5. 数据库系统概念总结:第四章 中级SQL

    周末无事水文章,期末备考的总结资料 第四章 中级SQL 4.1 连接表达式 4.1.1 连接条件 select * from student join takes on student.ID = ta ...

  6. mysql 事物状态有几种_mysql第三章 事务以及日志

    mysql第三章 事务以及日志 一. 事物简介 每条DDL DCL语句都是事务. 每个begin 到coomit语句是一个事务 二. 事物特性ACID以及开启方式 1. 原子性(A),部成功执行或全部 ...

  7. 19年8月 字母哥 第四章 常用web开发数据库框架 不要用公司网络加载不出来 用热点!!!

    第四章 常用web开发数据库框架 4.1.整合Spring JDBC操作数据 4.2 Spring JDBC多数据源的实现 4.3.Spring JDBC JTA实现分布式事务 4.4.ORM主流框架 ...

  8. 《深入理解分布式事务》第一章 事务的基本概念

    <深入理解分布式事务>第一章 事务的基本概念 文章目录 <深入理解分布式事务>第一章 事务的基本概念 一.事务的特性 1.原子性 2.一致性 3.隔离性 4.持久性 二.事务的 ...

  9. 【数据库】第四章 JDBC、MyBatis

    第四章 JDBC.MyBatis 文章目录 第四章 JDBC.MyBatis 一.JDBC 1.介绍 2.架构 3.常用接口 4.操作流程 5.模拟登录功能 一.MyBatis 1.导入 pom.xm ...

最新文章

  1. 【青少年编程】【三级】换装
  2. POI处理Excel中的日期数据类型
  3. Java IO: 网络
  4. 学习究竟是为了什么?
  5. 诗人也出数学题,出的有趣又深刻
  6. python爬取网易云音乐_爬取网易云音乐评论(一)——用python执行JS脚本
  7. 语音数字信号处理与分析及Matlab实现
  8. 【服务器数据恢复】服务器误删除ESXi虚拟机的数据恢复案例
  9. html5 pacs浏览,基于HTML5的PACS--HTML5图像处理
  10. js将html转为word文档,js将html导出到word文档(含echarts图表)
  11. 《软件方法》第8章 分析 之 分析类图(2)
  12. 【问题解决】电脑能用QQ但是打不开网页
  13. android github轮播图,Android使用开源框架ANDROID-IMAGE-INDICATOR实现图片轮播部署
  14. PL/SQL(显示游标):查询部门为20的(所有员工信息)
  15. 听说现在美女都流行吃“脏东西”了,有钱都不一定买得到...丨钛空舱
  16. Java筑基——反射(1):基本类周边信息获取
  17. 游程编码用matlab实现代码_二值图像游程编码matlab代码
  18. 图片/视频url 转 File Blob
  19. 内存分析工具打开报错解决方法An internal error occurred during: “Parsing heap dump from
  20. Python3,爬虫有多简单,一个库,一行代码,就OK, 你确定不来试试?

热门文章

  1. 【报告分享】2020直播电商生态白皮书.pdf(附下载链接)
  2. 剑指offer 面试题63. 股票的最大利润
  3. matlab通用程序,三次样条差值-matlab通用程序
  4. k-means聚类代码实现
  5. 斯坦福李飞飞CS231n笔记1计算机视觉概述与历史背景
  6. 吴恩达|机器学习作业3.1前馈神经网络
  7. 你是如何管理你的时间的?-----时间管理与树的遍历
  8. Hibernate的transaction嵌套
  9. python实现播放音乐_python实现简易云音乐播放器
  10. app 缓存html页面,HTML5本地存储VS App缓存离线网站浏览