一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|編程技術|正則表達式|

服務器之家 - 編程語言 - JAVA教程 - Spring Boot 基于注解的 Redis 緩存使用詳解

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

2020-09-30 15:35catoop JAVA教程

本篇文章主要介紹了Spring Boot 基于注解的 Redis 緩存使用詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

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

一、創(chuàng)建 Caching 配置類

RedisKeys.Java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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
 
  // 根據(jù)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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
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;
 
/**
 * 注解式環(huán)境管理
 *
 * @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() {
 
      /**
       * 對參數(shù)進行拼接后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分鐘
 
    // 根據(jù)key設定具體的緩存時間,key統(tǒng)一放在常量類RedisKeys中
    rcm.setExpires(redisKeys.getExpiresMap());
 
    List<String> cacheNames = new ArrayList<String>(redisKeys.getExpiresMap().keySet());
    rcm.setCacheNames(cacheNames);
 
    return rcm;
  }
 
}

二、創(chuàng)建需要緩存數(shù)據(jù)的類

TestService.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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自動生成,生成規(guī)則詳見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 也可以配置表達式根據(jù)我們傳遞的參數(shù)值判斷是否需要緩存。

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

三、測試方法

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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();
  }
}

至此完畢!

最后說一下,這個 @Cacheable 基本是可以放在所有方法上的,Controller 的方法上也是可以的(這個我沒有測試 ^_^)。

源碼下載地址:http://git.oschina.net/catoop/springboot-cache-redis

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

原文鏈接:http://blog.csdn.net/catoop/article/details/71275350

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 欧美一区二区三区四区五区六区 | 精品一久久香蕉国产线看播放 | 国产一级大片免费看 | 偷偷狠狠的日日高清完整视频 | 天堂在线中文字幕 | 精品国产在天天线在线麻豆 | 猫咪色网 | 日比免费视频 | 国产午夜精品福利 | 小女生RAPPER入口 | 欧美腐剧mm在线观看 | 性关系免费视频 | 天天做天天爱天天综合网 | 菠萝视频在线完整版 | 67194在线免费观看 | 国产亚洲精品九九久在线观看 | 日本xxoo动图网站欧美 | 欧美一级专区免费大片俄罗斯 | 波多野结衣被绝伦强在线观看 | 韩日理论片 | 亚洲欧美视频在线播放 | 亚洲第一区se | 男人躁女人过程 | 红色毛片 | 明星裸乳照无奶罩 | 色播影院性播影院私人影院 | 欧美日韩国内 | 午夜影院c绿象 | 欧美搞逼视频 | 国产欧美亚洲精品第一页青草 | 亚洲精品中文字幕在线 | 日韩欧美国产综合精品 | a免费看 | 日韩亚洲国产欧美精品 | 日本xxx在线观看免费播放 | 2012年免费中文视频 | 男人女人性生活视频 | 日出水了特别黄的视频 | 91精品国产综合久久香蕉 | 亚洲乱码尤物193yw在线播放 | 色综合久久丁香婷婷 |