最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot詳解整合Redis緩存方法

 更新時間:2022年07月15日 10:53:51   作者:悠然予夏  
本文主要介紹了SpringBoot整合Redis緩存的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

1、Spring Boot支持的緩存組件

在Spring Boot中,數(shù)據(jù)的緩存管理存儲依賴于Spring框架中cache相關(guān)的org.springframework.cache.Cache和org.springframework.cache.CacheManager緩存管理器接口。

如果程序中沒有定義類型為CacheManager的Bean組件或者是名為cacheResolver的CacheResolver緩存解析器,Spring Boot將嘗試選擇并啟用以下緩存組件(按照指定的順序):

(1)Generic

(2)JCache (JSR-107) (EhCache 3、Hazelcast、Infinispan等)

(3)EhCache 2.x

(4)Hazelcast

(5)Infinispan

(6)Couchbase

(7)Redis

(8)Caffeine

(9)Simple

上面按照Spring Boot緩存組件的加載順序,列舉了支持的9種緩存組件,在項目中添加某個緩存管理組件(例如Redis)后,Spring Boot項目會選擇并啟用對應(yīng)的緩存管理器。如果項目中同時添加了多個緩存組件,且沒有指定緩存管理器或者緩存解析器(CacheManager或者cacheResolver),那么Spring Boot會按照上述順序在添加的多個緩存中優(yōu)先啟用指定的緩存組件進行緩存管理。

剛剛講解的Spring Boot默認緩存管理中,沒有添加任何緩存管理組件能實現(xiàn)緩存管理。這是因為開啟緩存管理后,Spring Boot會按照上述列表順序查找有效的緩存組件進行緩存管理,如果沒有任何緩存組件,會默認使用最后一個Simple緩存組件進行管理。Simple緩存組件是Spring Boot默認的緩存管理組件,它默認使用內(nèi)存中的ConcurrentMap進行緩存存儲,所以在沒有添加任何第三方緩存組件的情況下,可以實現(xiàn)內(nèi)存中的緩存管理,但是我們不推薦使用這種緩存管理方式

2、基于注解的Redis緩存實現(xiàn)

在Spring Boot默認緩存管理的基礎(chǔ)上引入Redis緩存組件,使用基于注解的方式講解Spring Boot整合Redis緩存的具體實現(xiàn)

(1)添加Spring Data Redis依賴啟動器。在pom.xml文件中添加Spring Data Redis依賴啟動器

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

當(dāng)我們添加進redis相關(guān)的啟動器之后, SpringBoot會使用RedisCacheConfigratioin 當(dāng)做生效的自動配置類進行緩存相關(guān)的自動裝配,容器中使用的緩存管理器是RedisCacheManager , 這個緩存管理器創(chuàng)建的Cache為 RedisCache , 進而操控redis進行數(shù)據(jù)的緩存

(2)Redis服務(wù)連接配置

# Redis服務(wù)地址
spring.redis.host=127.0.0.1
# Redis服務(wù)器連接端口
spring.redis.port=6379
# Redis服務(wù)器連接密碼(默認為空)
spring.redis.password=

(3)對CommentService類中的方法進行修改使用@Cacheable、@CachePut、@CacheEvict三個注解定制緩存管理,分別進行緩存存儲、緩存更新和緩存刪除的演示

package com.lagou.service;
import com.lagou.pojo.Comment;
import com.lagou.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class CommentService {
    @Autowired
    private CommentRepository commentRepository;
    /**
     * @Cacheable: 將該方法查詢結(jié)果comment存放在SpringBoot默認緩存中
     * cacheNames: 起一個緩存的命名空間,對應(yīng)緩存的唯一標識
     * value:緩存結(jié)果   key:默認只有一個參數(shù)的情況下,key值默認就是方法參數(shù)值; 如果沒有參數(shù)或者多個參數(shù)的情況:會使用SimpleKeyGenerate來為生成key
     */
    @Cacheable(cacheNames = "comment", unless = "#result==null")
    public Comment findCommentById(Integer id) {
        Optional<Comment> byId = commentRepository.findById(id);
        if (byId.isPresent()) {
            Comment comment = byId.get();
            return comment;
        }
        return null;
    }
    // 更新方法
    @CachePut(cacheNames = "comment", key = "#result.id")
    public Comment updateComment(Comment comment) {
        commentRepository.updateComment(comment.getAuthor(), comment.getId());
        return comment;
    }
    // 刪除方法
    @CacheEvict(cacheNames = "comment")
    public void deleteComment(Integer id) {
        commentRepository.deleteById(id);
    }
}

以上 使用@Cacheable、@CachePut、@CacheEvict注解在數(shù)據(jù)查詢、更新和刪除方法上進行了緩存管理。

其中,查詢緩存@Cacheable注解中沒有標記key值,將會使用默認參數(shù)值comment_id作為key進行數(shù)據(jù)保存,在進行緩存更新時必須使用同樣的key;同時在查詢緩存@Cacheable注解中,定義了“unless = "#result==null"”表示查詢結(jié)果為空不進行緩存

控制層

package com.lagou.controller;
import com.lagou.pojo.Comment;
import com.lagou.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CommentController {
    @Autowired
    private CommentService commentService;
    @RequestMapping( "/findCommentById")
    public Comment findCommentById(Integer id) {
        Comment comment = commentService.findCommentById(id);
        return comment;
    }
    @RequestMapping(value = "/updateComment")
    public Comment updateComment(Comment comment) {
        Comment commentById = commentService.findCommentById(comment.getId());
        commentById.setAuthor(comment.getAuthor());
        return commentService.updateComment(commentById);
    }
    @RequestMapping(value = "/deleteComment")
    public void deleteComment(Integer id) {
        commentService.deleteComment(id);
    }
}

(4) 基于注解的Redis查詢緩存測試

可以看出,查詢用戶評論信息Comment時執(zhí)行了相應(yīng)的SQL語句,但是在進行緩存存儲時出現(xiàn)了IllegalArgumentException非法參數(shù)異常,提示信息要求對應(yīng)Comment實體類必須實現(xiàn)序列化(“DefaultSerializer requires a Serializable payload but received an object of type”)。

(5)將緩存對象實現(xiàn)序列化。

(6)再次啟動測試

訪問“http://localhost:8080/findCommentById?id=1”查詢id為1的用戶評論信息,并重復(fù)刷新瀏覽器查詢同一條數(shù)據(jù)信息,查詢結(jié)果

查看控制臺打印的SQL查詢語句

還可以打開Redis客戶端可視化管理工具Redis Desktop Manager連接本地啟用的Redis服務(wù),查看具體的數(shù)據(jù)緩存效果

執(zhí)行findById()方法查詢出的用戶評論信息Comment正確存儲到了Redis緩存庫中名為comment的名稱空間下。其中緩存數(shù)據(jù)的唯一標識key值是以“名稱空間comment::+參數(shù)值(comment::1)”的字符串形式體現(xiàn)的,而value值則是經(jīng)過JDK默認序列格式化后的HEX格式存儲。這種JDK默認序列格式化后的數(shù)據(jù)顯然不方便緩存數(shù)據(jù)的可視化查看和管理,所以在實際開發(fā)中,通常會自定義數(shù)據(jù)的序列化格式

(7) 基于注解的Redis緩存更新測試。

先通過瀏覽器訪問“http://localhost:8080/updateComment/1/shitou”更新id為1的評論作者名為shitou;

接著,繼續(xù)訪問“http://localhost:8080/findCommentById?id=1”查詢id為1的用戶評論信息

可以看出,執(zhí)行updateComment()方法更新id為1的數(shù)據(jù)時執(zhí)行了一條更新SQL語句,后續(xù)調(diào)用findById()方法查詢id為1的用戶評論信息時沒有執(zhí)行查詢SQL語句,且瀏覽器正確返回了更新后的結(jié)果,表明@CachePut緩存更新配置成功

(8)基于注解的Redis緩存刪除測試

通過瀏覽器訪問“http://localhost:8080/deleteComment?id=1”刪除id為1的用戶評論信息;

執(zhí)行deleteComment()方法刪除id為1的數(shù)據(jù)后查詢結(jié)果為空,之前存儲在Redis數(shù)據(jù)庫的comment相關(guān)數(shù)據(jù)也被刪除,表明@CacheEvict緩存刪除成功實現(xiàn)

通過上面的案例可以看出,使用基于注解的Redis緩存實現(xiàn)只需要添加Redis依賴并使用幾個注解可以實現(xiàn)對數(shù)據(jù)的緩存管理。另外,還可以在Spring Boot全局配置文件中配置Redis有效期,示例代碼如下:

# 對基于注解的Redis緩存數(shù)據(jù)統(tǒng)一設(shè)置有效期為1分鐘,單位毫秒
spring.cache.redis.time-to-live=60000

上述代碼中,在Spring Boot全局配置文件中添加了“spring.cache.redis.time-to-live”屬性統(tǒng)一配置Redis數(shù)據(jù)的有效期(單位為毫秒),但這種方式相對來說不夠靈活

3、基于API的Redis緩存實現(xiàn)

在Spring Boot整合Redis緩存實現(xiàn)中,除了基于注解形式的Redis緩存實現(xiàn)外,還有一種開發(fā)中常用的方式——基于API的Redis緩存實現(xiàn)。這種基于API的Redis緩存實現(xiàn),需要在某種業(yè)務(wù)需求下通過Redis提供的API調(diào)用相關(guān)方法實現(xiàn)數(shù)據(jù)緩存管理;同時,這種方法還可以手動管理緩存的有效期。

下面,通過Redis API的方式講解Spring Boot整合Redis緩存的具體實現(xiàn)

(1)使用Redis API進行業(yè)務(wù)數(shù)據(jù)緩存管理。在com.lagou.service包下編寫一個進行業(yè)務(wù)處理的類ApiCommentService

package com.lagou.service;
import com.lagou.pojo.Comment;
import com.lagou.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
@Service
public class ApiCommentService {
    @Autowired
    private CommentRepository commentRepository;
    @Autowired
    private RedisTemplate redisTemplate;
    // 使用API方式進行緩存,先去緩存中查找,緩存中有,直接返回;沒有查詢數(shù)據(jù)庫
    public Comment findCommentById(Integer id) {
        Object o = redisTemplate.opsForValue().get("comment_" + id);
        if (o != null) {
            return (Comment) o; // 查詢到數(shù)據(jù)
        } else {
            // 緩存中沒有,從數(shù)據(jù)庫中查詢
            Optional<Comment> byId = commentRepository.findById(id);
            if (byId.isPresent()) {
                Comment comment = byId.get();
                // 將查詢結(jié)果存入到緩存中,同時還可以設(shè)置有效期
                redisTemplate.opsForValue().set("comment_" + id, comment, 1, TimeUnit.DAYS); // 過期時間為一天
                return comment;
            }
        }
        return null;
    }
    // 更新方法
    public Comment updateComment(Comment comment) {
        commentRepository.updateComment(comment.getAuthor(), comment.getId());
        // 將更新數(shù)據(jù)進行緩存更新
        redisTemplate.opsForValue().set("comment_" + comment.getId(), comment, 1, TimeUnit.DAYS);
        return comment;
    }
    // 刪除方法
    public void deleteComment(Integer id) {
        commentRepository.deleteById(id);
        redisTemplate.delete("comment_" + id);
    }
}

(2)編寫Web訪問層Controller文件

package com.lagou.controller;
import com.lagou.pojo.Comment;
import com.lagou.service.ApiCommentService;
import com.lagou.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class ApiCommentController {
    @Autowired
    private ApiCommentService commentService;
    @RequestMapping( "/findCommentById")
    public Comment findCommentById(Integer id) {
        Comment comment = commentService.findCommentById(id);
        return comment;
    }
    @RequestMapping(value = "/updateComment")
    public Comment updateComment(Comment comment) {
        Comment commentById = commentService.findCommentById(comment.getId());
        commentById.setAuthor(comment.getAuthor());
        return commentService.updateComment(commentById);
    }
    @RequestMapping(value = "/deleteComment")
    public void deleteComment(Integer id) {
        commentService.deleteComment(id);
    }
}

基于API的Redis緩存實現(xiàn)的相關(guān)配置?;贏PI的Redis緩存實現(xiàn)不需要@EnableCaching注解開啟基于注解的緩存支持,所以這里可以選擇將添加在項目啟動類上的@EnableCaching進行刪除或者注釋

到此這篇關(guān)于SpringBoot詳解整合Redis緩存方法的文章就介紹到這了,更多相關(guān)SpringBoot Redis緩存內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot使用@Scheduled實現(xiàn)定時任務(wù)的并行執(zhí)行

    SpringBoot使用@Scheduled實現(xiàn)定時任務(wù)的并行執(zhí)行

    在SpringBoot中,如果使用@Scheduled注解來定義多個定時任務(wù),默認情況下這些任務(wù)將會被安排在一個單線程的調(diào)度器中執(zhí)行,這意味著,這些任務(wù)將會串行執(zhí)行,而不是并行執(zhí)行,本文介紹了SpringBoot使用@Scheduled實現(xiàn)定時任務(wù)的并行執(zhí)行,需要的朋友可以參考下
    2024-06-06
  • JAVA SPI特性及簡單應(yīng)用代碼實例

    JAVA SPI特性及簡單應(yīng)用代碼實例

    這篇文章主要介紹了JAVA SPI特性及簡單應(yīng)用代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-05-05
  • java中UDP簡單聊天程序?qū)嵗a

    java中UDP簡單聊天程序?qū)嵗a

    這篇文章主要介紹了java中UDP簡單聊天程序?qū)嵗a,有需要的朋友可以參考一下
    2013-12-12
  • java實現(xiàn)郵件發(fā)送詳解

    java實現(xiàn)郵件發(fā)送詳解

    這篇文章主要為大家詳細介紹了java實現(xiàn)郵件發(fā)送示例,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-03-03
  • SpringBoot實現(xiàn)WEB的常用功能案例詳解

    SpringBoot實現(xiàn)WEB的常用功能案例詳解

    這篇文章主要介紹了SpringBoot實現(xiàn)WEB的常用功能,本文將對Spring Boot實現(xiàn)Web開發(fā)中涉及的三大組件Servlet、Filter、Listener以及文件上傳下載功能以及打包部署進行實現(xiàn),需要的朋友可以參考下
    2022-04-04
  • 基于java編寫局域網(wǎng)多人聊天室

    基于java編寫局域網(wǎng)多人聊天室

    這篇文章主要為大家詳細介紹了基于java編寫局域網(wǎng)多人聊天室的相關(guān)資料,使用socket基于java編寫一個局域網(wǎng)聊天室,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-09-09
  • Java?spring?boot實現(xiàn)批量刪除功能詳細示例

    Java?spring?boot實現(xiàn)批量刪除功能詳細示例

    這篇文章主要給大家介紹了關(guān)于Java?spring?boot實現(xiàn)批量刪除功能的相關(guān)資料,文中通過代碼以及圖文將實現(xiàn)的方法介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2023-08-08
  • Java中常用時間的一些相關(guān)方法

    Java中常用時間的一些相關(guān)方法

    日期的使用多種多樣,但萬變不離其宗,下面這篇文章主要給大家介紹了關(guān)于Java中常用時間的一些相關(guān)方法,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下
    2021-10-10
  • 關(guān)于Jedis的用法以及Jedis使用Redis事務(wù)

    關(guān)于Jedis的用法以及Jedis使用Redis事務(wù)

    這篇文章主要介紹了關(guān)于Jedis的用法以及Jedis使用Redis事務(wù)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • Java判斷List中有無重復(fù)元素的方法

    Java判斷List中有無重復(fù)元素的方法

    今天小編就為大家分享一篇Java判斷List中有無重復(fù)元素的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-07-07

最新評論

外汇| 洛扎县| 香港 | 孝义市| 丽水市| 新沂市| 抚远县| 高碑店市| 承德县| 油尖旺区| 依兰县| 应用必备| 德昌县| 绩溪县| 南开区| 蒙自县| 弋阳县| 镶黄旗| 仁寿县| 海城市| 乐昌市| 黑龙江省| 宜兰县| 金坛市| 泾川县| 锡林浩特市| 三河市| 佛学| 固镇县| 离岛区| 嘉定区| 嘉义市| 扶绥县| 鸡泽县| 龙川县| 句容市| 阿坝县| 遵化市| 启东市| 禹城市| 自贡市|