当前位置: 代码网 > it编程>编程语言>Java > springboot如何开启缓存@EnableCaching(使用redis)

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

2024年11月08日 Java 我要评论
添加依赖 pom.xml<dependency> <groupid>org.springframework.boot</groupid> <art

添加依赖 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);
    }
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com