RedisTemplate常用使用說明 事務操作

2021-10-01 06:12:18 字數 1976 閱讀 6393

說明:下面以測試用例的形式說明 redis 事務在 springboot 中正確與錯誤的用法。首先,看一看當前測試用例的主體**:

import org.junit.test;

import org.junit.runner.runwith;

import org.springframework.beans.factory.annotation.autowired;

import org.springframework.boot.test.context.springboottest;

import org.springframework.dao.dataacces***ception;

import org.springframework.data.redis.core.redisoperations;

import org.springframework.data.redis.core.sessioncallback;

import org.springframework.data.redis.core.stringredistemplate;

import org.springframework.test.context.junit4.springrunner;

/** *

*/@runwith(springrunner.class)

public class redistranstest 執行以上測試用例,會丟擲如下的異常資訊:

error in execution; nested exception is io.lettuce.core.rediscommandexecutionexception: err exec without multi
這裡給出的錯誤資訊顯示:在執行 exec 命令之前,沒有執行 multi 命令。這很奇怪,我們明明在測試方法的第一句就執行了 multi。通過追蹤 multi、exec 等方法,我們可以看到如下的執行原始碼(spring-data-redis):

public t execute(rediscallbackaction, boolean exposeconnection, boolean pipeline)  else 

boolean existingconnection = transactionsynchronizationmanager.hasresource(factory);

原始碼中已經給出了答案:由於 enabletransactionsupport 屬性的預設值是 false,導致了每乙個 redisconnection 都是重新獲取的。所以,我們剛剛執行的 multi 和 exec 這兩個命令不在同乙個 connection 中。

解決上述示例的問題,最簡單的辦法就是讓 redistemplate 開啟事務支援,即設定 enabletransactionsupport 為 true 就可以了。測試**如下:

/**

** */

@test

public void testmultisuccess()

更常見的寫法仍是採用 redistemplate 的預設配置,即不開啟事務支援。但是,我們可以通過使用 sessioncallback,該介面保證其內部所有操作都是在同乙個session中。測試**如下:

/**

** */

@test

@suppresswarnings("all")

public void testsessioncallback()

};// [true, true, true]

system.out.println(stringredistemplate.execute(callback));

}

總結:我們在 springboot 中操作 redis 時,使用 redistemplate 的預設配置已經能夠滿足大部分的場景了。如果要執行事務操作,使用 sessioncallback 是比較好,也是比較常用的選擇

RedisTemplate操作Redis常用

redistemplate中定義了對5種資料結構操作 redistemplate.opsforvalue 操作字串 redistemplate.opsforhash 操作hash redistemplate.opsforlist 操作list redistemplate.opsforset 操作se...

redistemplate事務實踐

code public object testredismulti catch interruptedexception e now string operations.opsforvalue get testredismulti system.out.println now object rs o...

RedisTemplate快取用法小記

2 redis的引用包 org.springframework.data spring data redis 1.8.6.release 3 redistemplate裡面有如下幾種常用的形式 1 string型別 redistemplate.opsforvalue 2 list型別 rediste...