在SpringBoot中使用注解如何實(shí)現(xiàn)Redis緩存

在Spring Boot中使用注解如何實(shí)現(xiàn)redis 緩存?相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。

成都創(chuàng)新互聯(lián)長(zhǎng)期為上千家客戶提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊(duì)從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對(duì)不同對(duì)象提供差異化的產(chǎn)品和服務(wù);打造開放共贏平臺(tái),與合作伙伴共同營(yíng)造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為萬寧企業(yè)提供專業(yè)的成都做網(wǎng)站、成都網(wǎng)站建設(shè),萬寧網(wǎng)站改版等技術(shù)服務(wù)。擁有十余年豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開發(fā)。

一、創(chuàng)建 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 {

  // 測(cè)試 begin
  public static final String _CACHE_TEST = "_cache_test";// 緩存key
  public static final Long _CACHE_TEST_SECOND = 20L;// 緩存時(shí)間
  // 測(cè)試 end

  // 根據(jù)key設(shè)定具體的緩存時(shí)間
  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;

/**
 * 注解式環(huán)境管理
 * 
 * @author 單紅宇(CSDN catoop)
 * @create 2016年9月12日
 */
@Configuration
@EnableCaching
public class CachingConfig extends CachingConfigurerSupport {

  /**
   * 在使用@Cacheable時(shí),如果不指定key,則使用找個(gè)默認(rèn)的key生成器生成的key
   *
   * @return
   * 
   * @author 單紅宇(CSDN CATOOP)
   * @create 2017年3月11日
   */
  @Override
  public KeyGenerator keyGenerator() {
    return new SimpleKeyGenerator() {

      /**
       * 對(duì)參數(shù)進(jìn)行拼接后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) {
          // 如果不指定,默認(rèn)生成包含到鍵值中
          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);
    // 設(shè)置緩存默認(rèn)過期時(shí)間(全局的)
    rcm.setDefaultExpiration(1800);// 30分鐘

    // 根據(jù)key設(shè)定具體的緩存時(shí)間,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

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);
  }

  /**
   * 存儲(chǔ)在Redis中的key自動(dòng)生成,生成規(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 中配置的,那里是為了配置我們的緩存有效時(shí)間。其中 methodKeyGenerator 為 CachingConfig 中聲明的 KeyGenerator。

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

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

三、測(cè)試方法

下面代碼,隨便放一個(gè) 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;

/**
 * 測(cè)試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();
  }
}

看完上述內(nèi)容,你們掌握在Spring Boot中使用注解如何實(shí)現(xiàn)Redis 緩存的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!

文章標(biāo)題:在SpringBoot中使用注解如何實(shí)現(xiàn)Redis緩存
瀏覽路徑:http://muchs.cn/article0/jepeio.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供服務(wù)器托管、域名注冊(cè)、企業(yè)建站、全網(wǎng)營(yíng)銷推廣、App設(shè)計(jì)微信小程序

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站托管運(yùn)營(yíng)