springboot如何开启缓存@EnableCaching(使用redis)

 更新时间:2024年11月07日 16:19:10   作者:阿胜yss  
在Spring Boot项目中集成Redis主要包括添加依赖到pom.xml、配置application.yml中的Redis连接参数、编写配置类、在启动类上添加@EnableCaching注解以及测试接口的查询和缓存验证等步骤,首先,需要在pom.xml中添加spring-boot-starter-data-redis依赖

添加依赖 pom.xml

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

application.yml 配置redis连参数

spring:
  # redis 配置
  redis:
    # 地址
    host: 127.0.0.1
    # 端口,默认为6379
    port: 6379
    # 数据库索引
    database: 2
    # 密码
    password:
    # 连接超时时间
    timeout: 10s

配置类

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;


@Configuration
public class CacheConfig {

    /**
     * 最新版,设置redis缓存过期时间
     */
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        return new RedisCacheManager(
                RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
                this.getRedisCacheConfigurationWithTtl( 60) // 默认策略,未配置的 key 会使用这个
        );
    }

    private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
                RedisSerializationContext
                        .SerializationPair
                        .fromSerializer(jackson2JsonRedisSerializer)
        ).entryTtl(Duration.ofSeconds(seconds));
        return redisCacheConfiguration;
    }

}

启动类上 加 @EnableCaching 注解

测试

1.接口查询

2. 缓存查询验证

@ApiOperation(value = "根据ID获取详情",notes = "查询")
@Cacheable(cacheNames = "testaCache", key = "#id")
@RequestMapping(value = "/get/{id}",method = RequestMethod.GET)
public TestA get(@PathVariable Long id){
    log.info("进行了mysql查询");
    return testService.getById(id);
}
 @GetMapping("/get/redis/cache")
 @ApiOperation(value="查看redis缓存信息")
 public String getRedisCache(){
 	// 从IOC容器中通过类型获取bean  
     RedisCacheManager redisCacheManager = SpringUtils.getBean(RedisCacheManager.class);
     // 从IOC容器中通过名称获取bean
     RedisCacheManager redisCacheManager2 = SpringUtils.getBean("cacheManager");
     Cache demoCache = redisCacheManager.getCache("testaCache");
     log.info(demoCache.get(78, TestA.class)+"");
     return demoCache.getName();
 }

SpringUtils.class

import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public final class SpringUtils implements BeanFactoryPostProcessor, ApplicationContextAware 
{
    /** Spring应用上下文环境 */
    private static ConfigurableListableBeanFactory beanFactory;

    private static ApplicationContext applicationContext;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException 
    {
        SpringUtils.beanFactory = beanFactory;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException 
    {
        SpringUtils.applicationContext = applicationContext;
    }

    /**
     * 获取对象
     *
     * @param name
     * @return Object 一个以所给名字注册的bean的实例
     * @throws BeansException
     *
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException
    {
        return (T) beanFactory.getBean(name);
    }

    /**
     * 获取类型为requiredType的对象
     *
     * @param clz
     * @return
     * @throws BeansException
     *
     */
    public static <T> T getBean(Class<T> clz) throws BeansException
    {
        T result = (T) beanFactory.getBean(clz);
        return result;
    }

    /**
     * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
     *
     * @param name
     * @return boolean
     */
    public static boolean containsBean(String name)
    {
        return beanFactory.containsBean(name);
    }

    /**
     * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
     *
     * @param name
     * @return boolean
     * @throws NoSuchBeanDefinitionException
     *
     */
    public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException
    {
        return beanFactory.isSingleton(name);
    }

    /**
     * @param name
     * @return Class 注册对象的类型
     * @throws NoSuchBeanDefinitionException
     *
     */
    public static Class<?> getType(String name) throws NoSuchBeanDefinitionException
    {
        return beanFactory.getType(name);
    }

    /**
     * 如果给定的bean名字在bean定义中有别名,则返回这些别名
     *
     * @param name
     * @return
     * @throws NoSuchBeanDefinitionException
     *
     */
    public static String[] getAliases(String name) throws NoSuchBeanDefinitionException
    {
        return beanFactory.getAliases(name);
    }

    /**
     * 获取aop代理对象
     * 
     * @param invoker
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getAopProxy(T invoker)
    {
        return (T) AopContext.currentProxy();
    }

    /**
     * 获取当前的环境配置,无配置返回null
     *
     * @return 当前的环境配置
     */
    public static String[] getActiveProfiles()
    {
        return applicationContext.getEnvironment().getActiveProfiles();
    }

    /**
     * 获取配置文件中的值
     *
     * @param key 配置文件的key
     * @return 当前的配置文件的值
     *
     */
    public static String getRequiredProperty(String key)
    {
        return applicationContext.getEnvironment().getRequiredProperty(key);
    }
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Java泛型定义与用法实例详解

    Java泛型定义与用法实例详解

    这篇文章主要介绍了Java泛型定义与用法,结合实例形式较为详细的分析了Java中泛型的概念、原理、定义、使用方法及相关操作注意事项,需要的朋友可以参考下
    2018-08-08
  • Java实现冒泡排序与双向冒泡排序算法的代码示例

    Java实现冒泡排序与双向冒泡排序算法的代码示例

    这篇文章主要介绍了Java实现冒泡排序与双向冒泡排序算法的代码示例,值得一提的是所谓的双向冒泡排序并不比普通的冒泡排序效率来得高,注意相应的时间复杂度,需要的朋友可以参考下
    2016-04-04
  • java支付宝即时到帐提交订单功能

    java支付宝即时到帐提交订单功能

    这篇文章主要为大家详细介绍了java支付宝即时到帐提交订单功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-08-08
  • mybatis plus or and 的合并写法实例

    mybatis plus or and 的合并写法实例

    这篇文章主要介绍了mybatis plus or and 的合并写法实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-02-02
  • JSON Web Token在登陆中的使用过程

    JSON Web Token在登陆中的使用过程

    这篇文章主要介绍了JSON Web Token在登陆中的使用过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2025-04-04
  • Springmvc基于fastjson实现导包及配置文件

    Springmvc基于fastjson实现导包及配置文件

    这篇文章主要介绍了Springmvc基于fastjson实现导包及配置文件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-10-10
  • 深层剖析java应用开发中MyBayis缓存

    深层剖析java应用开发中MyBayis缓存

    这篇文章主要为大家深层剖析java开发中MyBayis缓存,文中讲解了Mybatis缓存的分类以及使用的方式,有需要的朋友可以借鉴参考下,希望可以有所帮助
    2021-09-09
  • Springboot设置文件上传大小限制的实现示例

    Springboot设置文件上传大小限制的实现示例

    Spring Boot工程嵌入的tomcat限制了请求的文件大小默认为1MB,单次请求的文件的总数不能大于10Mb,本文主要介绍了Springboot设置文件上传大小限制的实现示例,感兴趣的可以了解一下
    2023-11-11
  • kettle中使用js调用java类的方法

    kettle中使用js调用java类的方法

    这篇文章主要介绍了kettle中使用js调用java类的方法,本文讲解了注意事项和调用语法,需要的朋友可以参考下
    2015-05-05
  • Java编程接口调用的作用及代码分享

    Java编程接口调用的作用及代码分享

    这篇文章主要介绍了Java编程接口调用的作用及代码分享,具有一定参考价值,需要的朋友可以了解下。
    2017-11-11

最新评论