SpringBoot進階教程(五十六)整合Redis事物


Redis默認情況下,事務支持被禁用,必須通過設置setEnableTransactionSupport(true)為使用中的每個redistplate顯式啟用。這樣做會強制將當前重新連接綁定到觸發multi的當前線程。如果事務完成時沒有出錯,則調用exec。否則將調用Discard。一旦進入多個重新連接隊列,則寫入操作。所有只讀操作(如鍵)都通過管道連接到新的(非線程綁定的)重新連接。

以上內容來自官網內容的機器翻譯。

SpringBoot進階教程(二十八)整合Redis事物

v准備工作

學習本章節之前,建議依次閱讀以下文章,更好的串聯全文內容,如已掌握以下列出知識點,請跳過:

v事物配置

package com.demo.Redis;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * Created by toutou on 2019/2/16.
 */
@Configuration
@EnableTransactionManagement
public class RedisTranConfig {
    @Bean
    public StringRedisTemplate customStringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        template.setEnableTransactionSupport(true);
        return template;
    }
}

v接口測試

    @Autowired
    StringRedisTemplate template;

    @Transactional
    @RequestMapping(value = "/testredistran1")
    public String testRedisTran1()
    {
        template.opsForValue().set("test1a", "test1a");
        template.opsForValue().set("test1b", "test1b");
        template.opsForValue().set("test1c", "test1c");
        return "1";
    }

    @Transactional
    @RequestMapping(value = "/testredistran2")
    public String testRedisTran2()
    {
        template.opsForValue().set("test2a", "test2a");
        template.opsForValue().set(null, "test2b");
        template.opsForValue().set("test2c", "test2c");
        return "2";
    }

SpringBoot進階教程(二十八)整合Redis事物

分別請求http://localhost:8081/testredistran1和http://localhost:8081/testredistran2,可以發現test2a並沒有被寫入到Redis中。

v其它方法

    @RequestMapping(value = "/testredistran3")
    public String testRedisTran3()
    {
        //開啟事務
        template.multi();
        template.opsForValue().set("test3a", "test3a");
        template.opsForValue().set(null, "test3b");
        template.opsForValue().set("test3c", "test3c");
        //關閉事務
        template.exec();
        return "3";
    }

 Redis為單進程單線程模式,采用隊列模式將並發訪問變成串行訪問,Redis對事物支持不會很復雜,當一個客服端連接Redis服務時,發出了MULTI命令時,這個連接會進入事物,在執行MULTI命令之后,執行所有的命令都不會執行,會先放到一個隊列中,會提示正在Query,當最后執行EXEC命令之后,Redis會按照之前的進入隊列的順序,執行命令。

v源碼地址

https://github.com/toutouge/javademosecond/tree/master/hellospringboot


作  者:請叫我頭頭哥
出  處:http://www.cnblogs.com/toutou/
關於作者:專注於基礎平台的項目開發。如有問題或建議,請多多賜教!
版權聲明:本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接。
特此聲明:所有評論和私信都會在第一時間回復。也歡迎園子的大大們指正錯誤,共同進步。或者直接私信
聲援博主:如果您覺得文章對您有幫助,可以點擊文章右下角推薦一下。您的鼓勵是作者堅持原創和持續寫作的最大動力!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM