关于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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 制作WIN7+XP+DOS+PE多系统启动光盘

    制作WIN7+XP+DOS+PE多系统启动光盘本文详细介绍了怎样制作自定义的多系统启动光盘的流程,从零开始!达到完成系统盘制作的目的。

    2022年7月26日
    16
  • tomcat7配置教程_Tomcat热部署

    tomcat7配置教程_Tomcat热部署1.Tomcat依赖于JDK,需要提前安装好JDK,参考另外一篇文章:JAVA安装部署2.到官网下载Tomcat7,解压到相关路径即可。Tomcat官网3.从Tomcat7之后的版本都不需要配置环境变量,在bin目录下,查看starup.bat:意思是如果bin目录下面存在catalina.bat文件,就可以访问tomcat页面了,代表安装成功了。PS:如果没…

    2025年6月13日
    2
  • ArcGIS二次开发基础教程(00):基础界面设计

    ArcGIS二次开发基础教程(00):基础界面设计ArcGIS二次开发基础教程(00):基础界面设计(开发环境:VS2010+ArcEngine10.2+C#;鉴于学习ArcGIS二次开发的同学都有一定的WinForm开发和ArcGIS软件使用基础,故此教程不再对一些基础内容作详细阐述)首先新建一个Windows窗体应用程序,设置Size为(700,450),再添加一个MenuStrip,输入文件,如图:添加一个ToolB…

    2022年7月23日
    13
  • 向量三重积的几何意义_向量三重积

    向量三重积的几何意义_向量三重积定义同一个线性空间可定义不同的内积。选择复线性空间上的内积实内积空间性质向量长度向量长度性质Cauchy-Schwartz不等式Cauchy-Schwartz不等式推论度量矩阵只要告诉一组基下任意两个向量的内积,就会形成一个度量矩阵。那么随便拿一个向量,都知道它的坐标,这两个向量的内积就是右边的xTGyx^TGyxTGy。如果GGG为单位矩阵,那么<a,b><a,b><a,b>内积就等于他们坐标的内积。G为单位矩阵

    2022年8月30日
    3
  • ■ 直接调用阿里云视频点播API实现视频播放

    ■ 直接调用阿里云视频点播API实现视频播放

    2021年3月12日
    138
  • java8 list转换对象_Java8将List对象转换Map「建议收藏」

    java8 list转换对象_Java8将List对象转换Map「建议收藏」基于Java8的函数式编程概念,去实现List转换MappublicclassDemoMian2{publicstaticvoidmain(String[]args){ListusersList=newArrayList();Usersusers=newUsers();users.setId(1L);users.setName(“张三”);users.setSex(…

    2022年5月16日
    301

发表回复

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

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