• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号
您的位置:首页 > 程序设计 >Java > Spring Boot 基于注解的 Redis 缓存使用详解

Spring Boot 基于注解的 Redis 缓存使用详解

作者:catoop 字体:[增加 减小] 来源:互联网 时间:2017-05-28

catoop 通过本文主要向大家介绍了spring boot redis,spring boot集成redis,spring boot连接redis,spring boot 缓存,spring boot教程等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

看文本之前,请先确定你看过上一篇文章《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;
  }
}

</div>

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

}

</div>

二、创建需要缓存数据的类

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

</div>

说明一下,其中 @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();
  }
}

</div>

至此完毕!

最后说一下,这个 @Cacheable 基本是可以放在所有方法上的,Controller 的方法上也是可以的(这个我没有测试 ^_^)。

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

</div>
分享到:QQ空间新浪微博腾讯微博微信百度贴吧QQ好友复制网址打印

您可能想查找下面的文章:

  • Spring Boot 基于注解的 Redis 缓存使用详解
  • Spring Boot Redis 集成配置详解
  • spring boot(三)之Spring Boot中Redis的使用
  • Spring整合Redis完整实例代码
  • spring boot与redis 实现session共享教程
  • Spring Boot中Redis数据库的使用实例
  • Spring Boot集成Redis实现缓存机制(从零开始学Spring Boot)
  • Spring Boot 基于注解的 Redis 缓存使用详解
  • Spring Boot Redis 集成配置详解
  • spring boot(三)之Spring Boot中Redis的使用

相关文章

  • 2017-05-28Hibernate映射之基本类映射和对象关系映射详解
  • 2017-05-28详解Spring+Hiernate整合
  • 2017-05-28Java实现数组反转翻转的方法实例
  • 2017-05-28详解Java5、Java6、Java7的新特性
  • 2017-05-28老生常谈java中的数组初始化
  • 2017-05-28java利用java.net.URLConnection发送HTTP请求的方法详解
  • 2017-05-28Java中的对象和引用详解
  • 2017-05-28Java中正则表达式的使用和详解(上)
  • 2017-05-28java并发容器CopyOnWriteArrayList实现原理及源码分析
  • 2017-05-28Java基于正则表达式实现查找匹配的文本功能【经典实例】

文章分类

  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号

最近更新的内容

    • Java 条件控制与循环控制实例
    • spring+html5实现安全传输随机数字密码键盘
    • Java使用join方法暂停当前线程
    • MyBatis中的模糊查询语句
    • JAVA多线程并发下的单例模式应用
    • springMVC发送邮件的简单实现
    • 深入理解hibernate的三种状态
    • 图解JAVA中Spring Aop作用
    • SWT(JFace)体验之FormLayout布局
    • 详解Spring全局异常处理的三种方式

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有