SpringbootでredisTemplateトランザクションを開く2つの方法

1394 ワード

1.トランザクションサポートを開き、同じConnectionでコマンドを実行することを保証
redisTemplate.setEnableTransactionSupport(true);

Multiとexecの紹介:この2つの方法はRedisTemplate.JAvaクラスが提供するトランザクションメソッド.このメソッドを使用する前に、トランザクションを開いてから正常に使用する必要があります.
@Test
public void testMultiSuccess() {
 //       ,     Connection      
 stringRedisTemplate.setEnableTransactionSupport(true);

 stringRedisTemplate.multi();
 stringRedisTemplate.opsForValue().set("name", "qinyi");
 stringRedisTemplate.opsForValue().set("gender", "male");
stringRedisTemplate.opsForValue().set("age", "19");
System.out.println(stringRedisTemplate.exec());     // [true, true, true]
}

2.SessionCallbackにより、すべての操作が同じSessionで完了することを保証する
 SessionCallback<> callback = new SessionCallback<>() 

@Test @SuppressWarnings(“all”) public void testSessionCallback() { SessionCallback callback = new SessionCallback() { @Override public Object execute(RedisOperations operations) throws DataAccessException { operations.multi(); operations.opsForValue().set(“name”, “qinyi”); operations.opsForValue().set(“gender”, “male”); operations.opsForValue().set(“age”, “19”); return operations.exec(); } }; まとめ:SpringBootでRedisを操作する場合、RedisTemplateのデフォルト構成を使用すると、ほとんどのシーンを満たすことができます.トランザクション・オペレーションを実行する場合は、SessionCallbackを使用するとよいでしょう.また、一般的な選択です.