SpringBoot2.x整合redis,並開啓事務

概述

在SpringBoot中,開啓Redis的事務有兩種方式,一種是手動開啓,一種是使用@Transaction註解。html

springBoot框架及redis版本

<parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.0.2.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

配置Redis連接池

#redisConfig
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.redis.database=0
spring.redis.jedis.pool.max-idle=100
spring.redis.jedis.pool.min-idle=0

事務開啓方式

使用註解方式

1. redis配置類

//springBoot會自動配置redis,具體可參照RedisAutoConfiguration.java,可是默認的配置,沒有開啓事務,因此須要自定義
@Configuration
@EnableConfigurationProperties({RedisProperties.class})
public class RedisConfig {
    /**
     * 實例化 RedisTemplate 對象
     *
     * @return
     */
    @Bean
    public StringRedisTemplate customStringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        template.setEnableTransactionSupport(true);
        return template;
    }
}

2. 在須要開啓事務的方法上面加上註解

@Transactional(rollbackFor = Exception.class)
    public void mutiTest(Map<String,String> datas) throws Exception {
        redisTemplate.opsForValue().multiSet(datas);
        throw new Exception("custom exception");
    }

手動開啓

1. 無需配置,手動開啓事務

//開啓事務
        redisTemplate.multi();
        //do something
        //關閉事務
        redisTemplate.exec();

分享一篇關於redis事務的文章

redis事務詳解java

相關文章
相關標籤/搜索