<address id="ousso"></address>
<form id="ousso"><track id="ousso"><big id="ousso"></big></track></form>
  1. java語言

    Spring Boot基于注解的Redis緩存使用

    時間:2025-05-09 08:54:17 java語言 我要投稿
    • 相關推薦

    Spring Boot基于注解的Redis緩存使用

      Spring Boot是由Pivotal團隊提供的全新框架,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程。本文主要介紹了Spring Boot 基于注解的 Redis 緩存使用詳解,下面百分網小編帶大家一起來看看詳細內容,希望對大家有所幫助!想了解更多相關信息請持續關注我們應屆畢業生考試網!

      看文本之前,請先確定你看過上一篇文章《Spring Boot Redis 集成配置》并保證 Redis 集成后正常可用,因為本文是基于上文繼續增加的代碼。

      一、創建 Caching 配置類

      RedisKeys.Java

      package com.shanhy.example.redis;

      import java.util.HashMap;

      import java.util.Map;

      import javax.annotation.PostConstruct;

      import org.springframework.stereotype.Component;

      /**

      * 方法緩存key常量

      *

      * @author SHANHY

      */

      @Component

      public class RedisKeys {

      // 測試 begin

      public static final String _CACHE_TEST = "_cache_test";// 緩存key

      public static final Long _CACHE_TEST_SECOND = 20L;// 緩存時間

      // 測試 end

      // 根據key設定具體的緩存時間

      private Map<String, Long> expiresMap = null;

      @PostConstruct

      public void init(){

      expiresMap = new HashMap<>();

      expiresMap.put(_CACHE_TEST, _CACHE_TEST_SECOND);

      }

      public Map<String, Long> getExpiresMap(){

      return this.expiresMap;

      }

      }

      CachingConfig.java

      package com.shanhy.example.redis;

      import java.lang.reflect.Method;

      import java.util.ArrayList;

      import java.util.List;

      import org.springframework.cache.CacheManager;

      import org.springframework.cache.annotation.CachingConfigurerSupport;

      import org.springframework.cache.annotation.EnableCaching;

      import org.springframework.cache.interceptor.KeyGenerator;

      import org.springframework.cache.interceptor.SimpleKeyGenerator;

      import org.springframework.context.annotation.Bean;

      import org.springframework.context.annotation.Configuration;

      import org.springframework.data.redis.cache.RedisCacheManager;

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

      /**

      * 注解式環境管理

      *

      * @author 單紅宇(CSDN catoop)

      * @create 2016年9月12日

      */

      @Configuration

      @EnableCaching

      public class CachingConfig extends CachingConfigurerSupport {

      /**

      * 在使用@Cacheable時,如果不指定key,則使用找個默認的key生成器生成的key

      *

      * @return

      *

      * @author 單紅宇(CSDN CATOOP)

      * @create 2017年3月11日

      */

      @Override

      public KeyGenerator keyGenerator() {

      return new SimpleKeyGenerator() {

      /**

      * 對參數進行拼接后MD5

      */

      @Override

      public Object generate(Object target, Method method, Object... params) {

      StringBuilder sb = new StringBuilder();

      sb.append(target.getClass().getName());

      sb.append(".").append(method.getName());

      StringBuilder paramsSb = new StringBuilder();

      for (Object param : params) {

      // 如果不指定,默認生成包含到鍵值中

      if (param != null) {

      paramsSb.append(param.toString());

      }

      }

      if (paramsSb.length() > 0) {

      sb.append("_").append(paramsSb);

      }

      return sb.toString();

      }

      };

      }

      /**

      * 管理緩存

      *

      * @param redisTemplate

      * @return

      */

      @Bean

      public CacheManager cacheManager(RedisTemplate<String, Object> redisTemplate, RedisKeys redisKeys) {

      RedisCacheManager rcm = new RedisCacheManager(redisTemplate);

      // 設置緩存默認過期時間(全局的)

      rcm.setDefaultExpiration(1800);// 30分鐘

      // 根據key設定具體的緩存時間,key統一放在常量類RedisKeys中

      rcm.setExpires(redisKeys.getExpiresMap());

      List<String> cacheNames = new ArrayList<String>(redisKeys.getExpiresMap().keySet());

      rcm.setCacheNames(cacheNames);

      return rcm;

      }

      }

      二、創建需要緩存數據的類

      TestService.java

      package com.shanhy.example.service;

      import org.apache.commons.lang3.RandomStringUtils;

      import org.springframework.cache.annotation.Cacheable;

      import org.springframework.stereotype.Service;

      import com.shanhy.example.redis.RedisKeys;

      @Service

      public class TestService {

      /**

      * 固定key

      *

      * @return

      * @author SHANHY

      * @create 2017年4月9日

      */

      @Cacheable(value = RedisKeys._CACHE_TEST, key = "'" + RedisKeys._CACHE_TEST + "'")

      public String testCache() {

      return RandomStringUtils.randomNumeric(4);

      }

      /**

      * 存儲在Redis中的key自動生成,生成規則詳見CachingConfig.keyGenerator()方法

      *

      * @param str1

      * @param str2

      * @return

      * @author SHANHY

      * @create 2017年4月9日

      */

      @Cacheable(value = RedisKeys._CACHE_TEST)

      public String testCache2(String str1, String str2) {

      return RandomStringUtils.randomNumeric(4);

      }

      }

      說明一下,其中 @Cacheable 中的 value 值是在 CachingConfig的cacheManager 中配置的,那里是為了配置我們的緩存有效時間。其中 methodKeyGenerator 為 CachingConfig 中聲明的 KeyGenerator。

      另外,Cache 相關的注解還有幾個,大家可以了解下,不過我們常用的就是 @Cacheable,一般情況也可以滿足我們的大部分需求了。還有 @Cacheable 也可以配置表達式根據我們傳遞的參數值判斷是否需要緩存。

      注: TestService 中 testCache 中的 mapper.get 大家不用關心,這里面我只是訪問了一下數據庫而已,你只需要在這里做自己的業務代碼即可。

      三、測試方法

      下面代碼,隨便放一個 Controller 中

      package com.shanhy.example.controller;

      import org.slf4j.Logger;

      import org.slf4j.LoggerFactory;

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

      import org.springframework.data.redis.connection.jedis.RedisClient;

      import org.springframework.web.bind.annotation.GetMapping;

      import org.springframework.web.bind.annotation.RequestMapping;

      import org.springframework.web.bind.annotation.RestController;

      import com.shanhy.example.service.TestService;

      /**

      * 測試Controller

      *

      * @author 單紅宇(365384722)

      * @create 2017年4月9日

      */

      @RestController

      @RequestMapping("/test")

      public class TestController {

      private static final Logger LOG = LoggerFactory.getLogger(TestController.class);

      @Autowired

      private RedisClient redisClient;

      @Autowired

      private TestService testService;

      @GetMapping("/redisCache")

      public String redisCache() {

      redisClient.set("shanhy", "hello,shanhy", 100);

      LOG.info("getRedisValue = {}", redisClient.get("shanhy"));

      testService.testCache2("aaa", "bbb");

      return testService.testCache();

      }

      }

      至此完畢!

    【Spring Boot基于注解的Redis緩存使用】相關文章:

    詳解Spring Boot Redis集成配置07-18

    Spring Boot使用slf4j+logback記錄日志配置詳解08-16

    Spring Boot如何實現日志記錄SLF4J08-31

    如何使用php操作redis隊列實例09-15

    php中使用redis隊列操作實例代碼05-16

    用PHP基于Redis消息隊列實現發布微博的方法08-30

    CPU緩存的作用10-26

    PHP緩存技術10-08

    java的緩存機制07-29

    <address id="ousso"></address>
    <form id="ousso"><track id="ousso"><big id="ousso"></big></track></form>
    1. 日日做夜狠狠爱欧美黑人