SpringBoot集成redis與spring-cache

2020-09-07 佳雲大腦

未月廿三 | 作者

urlify.cn/nUn2Aj | 來源

spring基於註解的緩存

對於緩存聲明,spring的緩存提供了一組java註解:

  • @Cacheable:觸發緩存寫入。
  • @CacheEvict:觸發緩存清除。
  • @CachePut:更新緩存(不會影響到方法的運行)。
  • @Caching:重新組合要應用於方法的多個緩存操作。
  • @CacheConfig:設置類級別上共享的一些常見緩存設置。

@Cacheable

顧名思義,@Cacheable可以用來進行緩存的寫入,將結果存儲在緩存中,以便於在後續調用的時候可以直接返回緩存中的值,而不必再執行實際的方法。最簡單的使用方式,註解名稱=緩存名稱,使用例子如下:

@Cacheable(&34;)public Book findBook(ISBN isbn) {...}

一個方法可以對應兩個緩存名稱,如下:

@Cacheable({&34;, &34;})public Book findBook(ISBN isbn) {...}

@Cacheable的緩存名稱是可以配置動態參數的,比如選擇傳入的參數,如下: (以下示例是使用SpEL聲明,如果您不熟悉SpEL,可以閱讀Spring Expression Language)

@Cacheable(cacheNames=&34;, key=&isbn&34;books&34;34;)public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)@Cacheable(cacheNames=&34;, key=&isbn)&34;book&34;34;)public Book findBook(String name)@Cacheable(cacheNames=&34;, condition=&name.length() < 32&34;34;)public Book findBook(String name)

@Cacheable還可以設置:keyGenerator(指定key自動生成方法),cacheManager(指定使用的緩存管理),cacheResolver(指定使用緩存的解析器)等,這些參數比較適合全局設置,這裡就不多做介紹了。

@CachePut註解

@CachePut:當需要更新緩存而不幹擾方法的運行時 ,可以使用該註解。也就是說,始終執行該方法,並將結果放入緩存,註解參數與@Cacheable相同。以下是一個簡單的例子:

@CachePut(cacheNames=&34;, key=&isbn&34;books&34;books&34;primary&34;secondary&34;34;) })public Book importBooks(String deposit, Date date)

@CacheConfig註解

@CacheConfig:緩存提供了許多的註解選項,但是有一些公用的操作,我們可以使用@CacheConfig在類上進行全局設置。以下是個簡單的例子:

@CacheConfig(&34;)    public class BookRepositoryImpl implements BookRepository {            @Cacheable        public Book findBook(ISBN isbn) {...}    }

可以共享緩存名稱,統一配置KeyGenerator,CacheManager,CacheResolver。

實例

來看看我們在springboot中怎麼使用redis來作為緩存吧.

1.在pom.xml引入redis依賴

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

2.springboot集成redis配置文件(在本地啟動的redis),在springboot中使用redis,只要配置文件寫有redis配置,代碼就可以直接使用了。

spring:  redis:    database: 0  Connection URL. Overrides host, port, and password. User is ignored. Example: redis://user:password@example.com:6379    url: redis://user:@127.0.0.1:6379     host: 127.0.0.1  Login password of the redis server.    port: 6379  Whether to enable SSL support.    timeout: 5000 34;.&34;.&34;keyGenerator=&34;app:machineList:goods&34;神器榜單--查詢關聯關係及商品&34;查詢關聯關係及商品&34;inputVO&34;查詢商品模板(goodsId不用填寫,首次查詢使用category和typeTagFirst,點擊一級標籤查詢傳遞category和typeTagFirst和typeTagSecond)&34;GoodsModelRelatedInputVO&34;queryGoodsModels&34;&39;+39;:machineList-&inputVO.getTypeTagFirst()+&39;+34;)public WebResult queryGoodsModels(@RequestBody @Valid GoodsModelRelatedInputVO inputVO) {    List<TreeModel> list = relatedService.queryGoodsModels(inputVO);    return WebResult.getInstance().success(list);}

清除緩存

@ApiOperation(value = &34;, notes = &34;)@ApiImplicitParam(name = &34;, value = &34;, required = true, dataType = &34;)@PostMapping(&34;)@CacheEvict(value = Constants.APP_QUERY_GOODS,allEntries = true)public WebResult addTypeTagModel(@RequestBody List<TypeTag> typeTags) {    typeTagModelService.addTypeTagModel(typeTags);    return WebResult.getInstance().operateSuccess();}@ApiOperation(value = &34;, notes = &34;)@ApiImplicitParam(name = &34;, value = &34;, required = true, dataType = &34;)@PostMapping(&34;)@CacheEvict(value = Constants.APP_QUERY_GOODS,allEntries = true)public WebResult deleteTypeTagModel(@RequestBody @Valid TypeTagModelDelInputVO inputVO) {    Boolean flag = typeTagModelService.deleteTypeTagModel(inputVO);    return WebResult.getInstance().operateSuccess();}@ApiOperation(value = &34;, notes = &34;)@ApiImplicitParam(name = &34;, value = &34;, required = true, dataType = &34;)@PostMapping(&34;)@CacheEvict(value = Constants.APP_QUERY_GOODS,allEntries = true)public WebResult insertGoodsModelRelated(@RequestBody @Valid List<GoodsModelRelated> goodsModelRelateds) {    relatedService.insertGoodsModelRelatedBatch(goodsModelRelateds);    return WebResult.getInstance().operateSuccess();}@ApiOperation(value = &34;, notes = &34;)@DeleteMapping(&34;)@CacheEvict(value = Constants.APP_QUERY_GOODS,allEntries = true)public WebResult deleteGoodsModelRelatedBatch(@RequestBody @Valid @ApiParam(name = &34;, value = &34;, required = true)List<Long> ids) {    relatedService.deleteGoodsModelRelatedBatch(ids);    return WebResult.getInstance().operateSuccess();}

說明

在查詢的時候將數據進行緩存,在進行數據更改的時候,根據 APP_QUERY_GOODS = &34;名字將此名字下緩存的數據刪掉

APP_QUERY_GOODS的命名使用&34;分隔,&34;在rdm中查看的時候就是三個層級

app第一層級,machineList第二層級,goods第三層級

然後後面會以key命名的規則添加

value命名的和key命名的中間以&34;分隔

相關焦點

  • 集成Redis、mybatis、springboot
    這兒我們就不用jedis了,spring對redis也有支持,我們就用spring-boot-starter-data-redis來整合redis。--https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis --><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis
  • spring data redis集成以及session共享
    redis一些主流的開源框架也很好的集成了redis,Spring生態下的Spring Data系列集成了Redis,使用起來非常方便。簡單三步集成。;/dependency>springboot會自動給我們在啟動類添加上註解@EnableRedisHttpSession,該註解會在底層會創建一個 springSessionRepositoryFilter 的過濾器,該過濾器實現了 Filter接口,過濾器將 HttpSession 替換為spring session支持的方式,springboot幫我們實現了所有請求會經過
  • Spring極速集成註解redis實踐
    Spring 團隊對 Jedis 進行了封裝,獨立為 spring-data-redis 項目,配合 spring 特性併集成 Jedis 的一些命令和方法。本文重點描述集成過程,能讓你迅速的通過 spring-data-redis 將 redis 集成到 spring 項目中,畢竟大家都忙的。1. 添加項目依賴<!
  • Spring 極速集成註解 Redis 實踐
    Spring 團隊對 Jedis 進行了封裝,獨立為 spring-data-redis 項目,配合 spring 特性併集成 Jedis 的一些命令和方法。本文重點描述集成過程,能讓你迅速的通過 spring-data-redis 將 redis 集成到 spring 項目中,畢竟大家都忙的。1. 添加項目依賴<!
  • springboot 2.1+shiro+redis+layUI後臺權限管理系統
    springboot 2.1 + shiro + redis + layUI 後臺管理系統本項目的功能模塊spring boot 2.1 + mybatis後臺管理系統框架;layUI前端界面;shiro權限控制
  • SpringBoot實戰(四):整合Redis
    -- redis --><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency
  • Spring Boot 如何快速集成 Redis?
    Spring Boot 如何快速集成 Redis?沒錯,棧長本文教你,讓大家少走彎路!添加依賴使用像 Redis 這類的 NoSQL 資料庫就必須要依賴 spring-data-redis 這樣的能力包,開箱即用,Spring Boot 中都封裝好了:引入spring-boot-starter-data-redis:
  • SpringBoot整合Redis消息隊列
    -- 集成redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <
  • SpringBoot2.0實戰(23)整合Redis之集成緩存SpringDataCache
    添加依賴引入 Spring Boot Starter 父工程添加 redisspring.cache.type 配置緩存類型,默認為 simple,配置使用 redis 作為緩存中間件,只需要配置 spring.cache.type 屬性為 redis 即可
  • 從零搭建Spring Boot腳手架:整合Redis作為緩存
    依賴集成目前只需要引入下面的依賴即可: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId></dependency
  • 使用spring cache讓我的接口性能瞬間提升了
    對於java開發而言,首先的緩存當然是redis。我們仔細分析了一下原因,發現了兩個主要的優化點:去掉多餘的接口日誌列印 和 分類接口引入redis cache做一次二級緩存。日誌列印我在這裡就不多說了,不是本文的重點,我們重點說一下redis cache。
  • SpringBoot利用spring-boot-starter-data-redis整合Redis
    redis作用在內存,性能極高。SpringBoot同樣可以把Redis整合到項目裡。首先,第一步就是為項目添加Redis依賴。在SpringBoot下有spring-boot-starter-data-redis,使用Redis就相當的簡單。第二步添加上Redis配置信息。
  • 開源吧,整合Redis作為緩存搭建Spring Boot框架
    依賴集成目前只需要引入下面的依賴即可: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis
  • springboot實現session共享redis中保存
    -- 引入springboot&redis整合場景 -->        <dependency>            <groupId>org.springframework.boot
  • springboot jwt redis實現token刷新
    -- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency>
  • Redis整合Spring項目搭建實例
    :1.0.13' compile 'redis.clients:jedis:2.7.0' compile 'org.springframework.data:spring-data-redis:1.5.0.RELEASE' testCompile group: 'junit', name: 'junit', version: '4.11'}task wrapper(type: Wrapper
  • Redis實現Spring緩存
    ; </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>
  • Springboot快速簡單的使用redis
    嘗試操作一下在window環境下,idea開發工具,在springboot項目中使用redis的簡單操作。1.下載windows環境下的redis包,解壓後將redis路徑配置到系統環境變量中。2.啟動redis服務,在cmd中執行redis-server。
  • 深入Spring Boot (十一):整合Redis詳解
    整合Redis,可以通過使用spring-boot-starter-data-redis,這種方式下,Spring Boot默認使用的Redis客戶端是Lettuce。'在application.properties或application.yml中添加Redis服務配置,例如在application.properties中添加如下基礎配置:#Redis伺服器主機地址spring.redis.host=127.0.0.1#Redis服務連接密碼spring.redis.password=
  • spring-boot-plus 1.0.0 發布,後臺快速開發框架
    spring-boot-plus 是一套集成 spring boot 常用開發組件的後臺快速開發框架Purpose