【问题标题】:Spring Boot | Create custom caching annotation and implementation弹簧靴 |创建自定义缓存注释和实现
【发布时间】:2019-08-22 17:58:31
【问题描述】:

我想创建一个自定义 spring @Cachable 注释,我可以在其中以秒为单位定义过期时间。 问题是,我不知道如何在自定义注解中实现新方法“expiresInSec()”。

这是我自定义的@Cachable 注解:

@Retention(RetentionPolicy.RUNTIME)
@Target(
{ElementType.TYPE, ElementType.METHOD})
public @interface Cachable
{
    Cacheable cachable();

    // cache entry expires in 1 hour by default
    int expiresInSec() default 3600;
}

这是自定义注解的调用:

@Cachable(cachable = @Cacheable("WorkListRepository::getWorkList"), expiresInSec = 60)

但是 expireInSec 参数不起作用。我必须在哪里实现这个参数方法。

谢谢

【问题讨论】:

    标签: java spring spring-boot spring-annotations spring-cache


    【解决方案1】:

    扩展 Spring Cacheable 需要的不仅仅是在注释中添加额外的属性。您还需要扩展注释处理器的功能以在 Spring 中进行缓存。查看here 了解更多详情。

    Spring 缓存是一种抽象,需要缓存提供程序,并且通常在缓存级别设置到期时间(例如,Ehcache 每个缓存都有timeToLiveSeconds 参数)

    【讨论】:

    • 如果我使用 Ehcache,那么我必须为每个缓存的配置创建一个 xml 文件。对吗?
    • 我可以使用 Ehcache 和 spring 缓存吗?有注释吗?
    • 您将不得不使用一些提供程序。 Spring boot 检查类路径的依赖关系以自动确定提供者。例如。您可能在构建文件中提到了 Ehcache,然后 Spring Boot 将在运行时检查提供程序 jar。但是,默认情况下,Spring boot Ehcache 集成在配置文件之前不会被初始化(默认情况下不提供 ehcache.xml)。在此处查看带有 Ehcache 和 Spring boot 的 TTL 示例。 baeldung.com/spring-boot-ehcache
    • 是的,我也找到了这个 baeldung 页面,但我必须创建一个 xml 文件以使缓存到期。我想通过 @Cachable 注释定义缓存的到期时间。
    猜你喜欢
    • 1970-01-01
    • 2016-02-10
    • 2011-07-28
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    • 2022-06-20
    • 2018-04-02
    • 2018-02-14
    相关资源
    最近更新 更多