关于spring boot 事务

关于spring boot 事务

redis事务

  • redis最好的事务方式还是用它自己的watch 读数据,然后再用multi进行锁定,最后用exec执行,如果成功返回[null,true],如果失败返回操作结果[结果,false]
  • redis的事务很容易与mysql数据库的事务混在一起,尽量不要打开。默认redis的事务是关闭的。非要打开的可以 template.setEnableTransactionSupport(true);
  • 配置参考:

@Configuration

@EnableCaching

public class RedisConfig extends CachingConfigurerSupport {

    // slf4j logger

    private final static Logger logger = LoggerFactory.getLogger(RedisConfig.class);

    @Bean

    @Override

    public KeyGenerator keyGenerator() {

        logger.debug(“—–>>>>>[RedisConfig.keyGenerator]:Initializing Redis keyGenerator.”);

        return new KeyGenerator() {

            @Override

            public Object generate(Object target, Method method, Object… params) {

                StringBuilder sb = new StringBuilder();

                sb.append(target.getClass().getName());

                sb.append(method.getName());

                for (Object obj : params) {

                    sb.append(obj.toString());

                }

                return sb.toString();

            }

        };

    }

    @SuppressWarnings(“rawtypes”)

    @Bean

    public CacheManager cacheManager(RedisTemplate redisTemplate) {

        logger.debug(“—–>>>>>[RedisConfig.cacheManager]:Initializing simple Redis Cache manager.”);

        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);

        //todo 设置缓存过期时间

//        rcm.setDefaultExpiration(60 * 3);//秒

        return rcm;

    }

    /**

     * 不用理会 factory 警告!!!

     * todo 存对像时直接转成jsonString就行了,不需要用其它的序列化。

     *

     *

     * @param factory

     * @return

     */

    @Bean

    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {

        logger.debug(“—–>>>>>[RedisConfig.redisTemplate]:Initializing Redis Template.”);

        StringRedisTemplate template = new StringRedisTemplate(factory);

        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();

        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        jackson2JsonRedisSerializer.setObjectMapper(om);

        template.setValueSerializer(jackson2JsonRedisSerializer);

        template.afterPropertiesSet();

        return template;

    }

}

参考:

http://stackoverflow.com/questions/21664487/how-to-implement-transaction-in-spring-data-redis-in-a-clean-way

spring (boot)事务

spring 的事务主要用@Transactional注解。

有几点要特别注意:

  1. 指定rollbackFor参数,这个是显示指定回滚的条件,如rollbackFor = Exception.class,当方法抛异常时回滚,非常实用。
  2. 注意@Transactional只能作用在public的方法上
  3. @Transactional书写方便,尽可能写在最需要的地方,如某个方法上,而不是在整个类上
  4. 配置参考

@Configuration

@EnableTransactionManagement

@PropertySource(“classpath:/application-database-${spring.profiles.active}.properties”)

public class MyBatisConfig {

//    @Bean(name = “dataSource”) //!!!返回参数要是类,不是接口,否则它处无法使用!!!

//    @ConfigurationProperties(prefix = “spring.datasource”)

//    public DruidDataSource dataSource() throws SQLException {

//        return new DruidDataSource();

//    }

    /**

     * 直接使用properties里面的配置生成datasource

     */

    @Autowired

    private DataSource dataSource;

    @Bean

    public SqlSessionFactory sqlSessionFactory() throws Exception {

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

        sqlSessionFactoryBean.setDataSource(dataSource);

        //mybatis分页

        PageHelper pageHelper = new PageHelper();

        Properties props = new Properties();

        props.setProperty(“dialect”, “mysql”);

        props.setProperty(“reasonable”, “true”);

        props.setProperty(“supportMethodsArguments”, “true”);

        props.setProperty(“returnPageInfo”, “check”);

        props.setProperty(“params”, “count=countSql”);

        pageHelper.setProperties(props); //添加插件

        sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageHelper});

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        sqlSessionFactoryBean.setMapperLocations(resolver.getResources(“classpath:*/mybatis/*.xml”));

        return sqlSessionFactoryBean.getObject();

    }

    @Bean(name = “transactionManager”)

    public PlatformTransactionManager transactionManager() throws SQLException {

        return new DataSourceTransactionManager(dataSource);

    }

}

@EnableTransactionManagement 只需要这里指定一次就行了,其它地方不需要再指定,引用的时候自然会打开事务。

参考:http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/index.html#transaction-declarative-attransactional-settings

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/100424.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • USART与UART的区别

    USART(universalsynchronousasynchronousreceiverandtransmitte):通用同步异步收发器USART是一个串行通信设备,可以灵活地与外部设备进行全双工数据交换。UART(universalasynchronousreceiverandtransmitter):通用异步收发器异步串行通信口(UART)就是我们在…

    2022年4月3日
    71
  • react父子组件传值

    react父子组件传值react父子组件传值react父子组件传值一、父给子传值1.子组件是函数组件时,通过参数props接收2.子组件是类组件时,通过参数this.props接收二、子给父传值react父子组件传值一、父给子传值1.子组件是函数组件时,通过参数props接收2.子组件是类组件时,通过参数this.props接收二、子给父传值1.由父组件给子组件提供一个回调函数,传递给子组件;2.当子组件给父组件传值时,调用该回调函数3.父组件通过回调函数调用,拿到子组件传来的参数结果:点击按钮后

    2022年5月17日
    76
  • JScript内置对象Array中元素的删除问题

    JScript内置对象Array中元素的删除问题

    2021年7月22日
    59
  • カード名義_acwing题库

    カード名義_acwing题库原题链接给定一棵包含 n 个节点的有根无向树,节点编号互不相同,但不一定是 1∼n。有 m 个询问,每个询问给出了一对节点的编号 x 和 y,询问 x 与 y 的祖孙关系。输入格式输入第一行包括一个整数 表示节点个数;接下来 n 行每行一对整数 a 和 b,表示 a 和 b 之间有一条无向边。如果 b 是 −1,那么 a 就是树的根;第 n+2 行是一个整数 m 表示询问个数;接下来 m 行,每行两个不同的正整数 x 和 y,表示一个询问。输出格式对于每一个询问,若 x 是 y 的祖先则输

    2022年8月8日
    2
  • impala实战篇

    impala实战篇第 1 章 impala 基本概念 1 什么是 impalaCloude 公司推出 提供对 HDFS Hbase 数据的高性能 低延迟的交互式 SQL 查询功能 基于 Hive 使用内存计算 兼顾数据仓库 具有实时 批处理 多并发等优点 是 CDH 平台首选的 PB 级大数据实时查询分析引擎 1 1Impala 的优缺点 1 1 1 优点基于内存运算 不需要把中间结果写入磁盘 省掉了大量的 I O 开销 无需转换 MapReduce 直接访问存储在 HDFS HBase 中的数据进行作业调度 速度快 使用了支持

    2025年9月3日
    4
  • c#窗体应用程序怎么保存_importedfile用什么打开

    c#窗体应用程序怎么保存_importedfile用什么打开选择保存文件时先将文件名生成传入,点击OK和取消使用FileOK委托。///<summary>///另存文件对话框///</summary>///<paramname=”fileName”>想命名的文件名</param>///<returns>&lt…

    2022年10月8日
    4

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号