【问题标题】:redis transaction alongside jdbc transactionredis 事务和 jdbc 事务
【发布时间】:2021-01-20 04:16:16
【问题描述】:

在我们的应用程序中,我们同时使用 MySQL 服务器和 Redis 数据库。我们将 Redis 用作数据库,而不仅仅是缓存。我们在服务方法中同时使用它们,我想让方法 @Transactional 让 spring 管理我的事务。因此,如果在事务方法的中间抛出一个 RuntimeException,那么 Redis 和 MySQL 上的所有工作都会回滚。我遵循spring docs 并将我的@SpringBootApplication 类配置如下:

@SpringBootApplication
@EnableTransactionManagement
public class TransactionsApplication {

    @Autowired
    DataSource dataSource;

    public static void main(String[] args) {
        SpringApplication.run(TransactionsApplication.class, args);
    }

    @Bean
    public StringRedisTemplate redisTemplate() {
        StringRedisTemplate template = new StringRedisTemplate(redisConnectionFactory());
        // explicitly enable transaction support
        template.setEnableTransactionSupport(true);
        return template;
    }

    @Bean
    public LettuceConnectionFactory redisConnectionFactory() {
        return new LettuceConnectionFactory(new RedisStandaloneConfiguration("localhost", 6379));
    }

    @Bean
    public PlatformTransactionManager transactionManager() throws SQLException, IOException {
        return new DataSourceTransactionManager(dataSource);
    }
}

这是我的服务方法:

@Service
@RequiredArgsConstructor
@Slf4j
public class FooService {

   private final StringRedisTemplate redisTemplate;
   private final FooRepository fooRepository;

   @Transactional            
   public void bar() {

       Foo foo = Foo.builder()
               .id(1001)
               .name("fooName")
               .email("foo@mail.com")
               .build();
       fooRepository.save(foo);

       ValueOperations<String, String> values = redisTemplate.opsForValue();
       values.set("foo-mail", foo.getEmail());

   }

但是在调用TestService的测试方法后,MySQL db中没有用户,我认为这是因为它没有活动的事务。这个问题有什么解决方案吗?我应该使用 spring ChainedTransactionManager 类,然后如何使用?还是只能通过MULTI手动管理Redis事务?

【问题讨论】:

    标签: java mysql spring-boot redis spring-transactions


    【解决方案1】:

    在玩了FooService 类之后,我发现在旨在与 Redis 一起使用的服务方法中使用 @Transactional 并专门从 Redis 读取一个值(我认为大多数服务方法都应该从中读取一些值DB)在某种程度上是无用的,因为任何读取操作都会导致 null 值,这是因为 Redis 将事务的所有操作排队并在最后执行它们。总结一下,我认为使用MULTIEXEC 操作更可取,因为它可以更好地控制在Redis 中使用数据。 毕竟,任何使用 Redis 事务的建议都值得赞赏。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多