@RefreshScope导致@Scheduled失效

一、问题背景

需要在springboot项目中引入定时任务实现定时的功能,任务当中有一个参数是在nacos的配置中心中的,希望做到任务执行时可以动态的获取配置中的信息。

二、实现代码

配置文件

message:
  log:
    timeout: 30 #天

启动类

import com.botany.spore.liquibase.autoconfig.EnableLiquibase;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableLiquibase
@EnableScheduling // 开启定时任务功能
@SpringCloudApplication
@EnableFeignClients
public class InboxModelApplication {

    public static void main(String[] args) {
        SpringApplication.run(InboxModelApplication.class, args);
    }

}

调度任务

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * description: 调度
 *
 * @author: weirx
 * @time: 2021/4/30 11:30
 */
@Slf4j
@RefreshScope
@Component
public class HistoryLogDeleteTask {

    @Value("${message.log.timeout}")
    private String timeout;

    @Scheduled(cron = "*/10 * * * * ?")
    public void execute() {
        log.info("thread id:{}", Thread.currentThread().getId());
        this.deleteHistoryLog();
    }

    private void deleteHistoryLog() {
        DateTime dateTime = DateUtil.offsetDay(new Date(), Integer.valueOf(timeout));
        log.info("删除时间:{}", dateTime);
    }

}

三、问题描述

如上实现方式,发现在配置文件修改后,调度任务就停止了。

四、RefreshScope原理

4.1 Scope

想要了解RefreshScope,就要先了解Scope。
org.springframework.beans.factory.config.Scope是在spring中就存在的,而RefreshScope是springcloud对Scope的一种特殊实现,用于实现配置、实例的热加载。

Scope,也称作用域,在 Spring IoC 容器是指其创建的 Bean 对象相对于其他 Bean 对象的请求可见范围。在 Spring IoC 容器中具有以下几种作用域:基本作用域(singleton、prototype),Web 作用域(reqeust、session、globalsession),自定义作用域。

4.1.1 spring配置xml

Spring 的作用域在装配 Bean 时就必须在配置文件中指明,配置方式如下(以 xml 配置文件为例):

<!-- 具体的作用域需要在 scope 属性中定义 -->
<bean id="XXX" class="com.XXX.XXXXX" scope="XXXX" />

4.1.2 使用注解@Scope

下面是@Scope的源码:

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Scope {

    /**
     * Alias for {@link #scopeName}.
     * @see #scopeName
     */
    @AliasFor("scopeName")
    String value() default "";

    /**
     * Specifies the name of the scope to use for the annotated component/bean.
         * 为带有@Componet和@Bean注解,指定作用域名称
         * 
     * <p>Defaults to an empty string ({@code ""}) which implies
         * 默认是个空字符串
         *
     * {@link ConfigurableBeanFactory#SCOPE_SINGLETON SCOPE_SINGLETON}.
     * @since 4.2 从4.2开始可以指定以下作用域
     * @see ConfigurableBeanFactory#SCOPE_PROTOTYPE 多实例
          -- 每次获取Bean的时候会有一个新的实例
     * @see ConfigurableBeanFactory#SCOPE_SINGLETON 单例
          -- 全局有且仅有一个实例
     * @see org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST
         -- 表示该针对每一次HTTP请求都会产生一个新的bean,同时该bean仅在当前HTTP request内有效
     * @see org.springframework.web.context.WebApplicationContext#SCOPE_SESSION
         -- 表示该针对每一次HTTP请求都会产生一个新的bean,同时该bean仅在当前HTTP session内有效
     * @see #value
     */
    @AliasFor("value")
    String scopeName() default "";

    /**
     * Specifies whether a component should be configured as a scoped proxy
     * and if so, whether the proxy should be interface-based or subclass-based.
         * 指定是否应将组件配置为作用域代理*,如果是,则指定代理是基于接口还是基于子类
     * <p>Defaults to {@link ScopedProxyMode#DEFAULT}, which typically indicates
     * that no scoped proxy should be created unless a different default
     * has been configured at the component-scan instruction level.
         * 默认是DEFAULT,这表示在没有指定其他作用域配置事,不应该创建任何作用域代理
     * <p>Analogous to {@code <aop:scoped-proxy/>} support in Spring XML.
         * 类似于Spring XML中的{@code <aop:scoped-proxy />}支持
     * @see ScopedProxyMode
     */
    ScopedProxyMode proxyMode() default ScopedProxyMode.DEFAULT;
}

4.2 @RefreshScope

4.2.1 简单认识RefreshScope

/**
 * Convenience annotation to put a <code>@Bean</code> definition in
 * {@link org.springframework.cloud.context.scope.refresh.RefreshScope refresh scope}.
 * Beans annotated this way can be refreshed at runtime and any components that are using
 * them will get a new instance on the next method call, fully initialized and injected
 * with all dependencies.
 * 用这种方式注释的Bean可以在运行时刷新,并且正在使用*的任何组件都将在下一个方法调用上获得一个新实例,  
 * 并对其进行完全初始化并注入*所有依赖项
 *
 * @author Dave Syer
 *
 */
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Scope("refresh")
@Documented
public @interface RefreshScope {

    /**
     * @see Scope#proxyMode()
     * @return proxy mode
     */
    ScopedProxyMode proxyMode() default ScopedProxyMode.TARGET_CLASS;

}

如上所示,该注解使用了@Scope,并默认了ScopedProxyMode.TARGET_CLASS; 属性,此属性的功能就是在创建一个代理,在每次调用的时候都用它来调用GenericScope get 方法来获取对象。GenericScope是SpringCloud对Scope的一个实现,Scope的源码如下,我们主要关注get方法:

    public interface Scope {
        /**
         * description: 核心操作,从基础范围返回带有指定名称的对象。
         * @param name 对象名称
         * @param objectFactory 函数式接口对象,用于创建对象
         */
        Object get(String name, ObjectFactory<?> objectFactory);

        /**
         * description: 从基本作用域删除指定对象
         * @param name
         * @return: java.lang.Object
         */
        @Nullable
        Object remove(String name);

        void registerDestructionCallback(String name, Runnable callback);

        @Nullable
        Object resolveContextualObject(String key);

        @Nullable
        String getConversationId();

    }
}

4.2.2 如何刷新的?

通过跟踪代码,发现是从以下位置开始整个刷新过程,下面这个监听会时时等待刷新的消息推送:

public class RefreshEventListener implements SmartApplicationListener {

    private static Log log = LogFactory.getLog(RefreshEventListener.class);

    private ContextRefresher refresh;

    private AtomicBoolean ready = new AtomicBoolean(false);

    public RefreshEventListener(ContextRefresher refresh) {
        this.refresh = refresh;
    }

    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
        return ApplicationReadyEvent.class.isAssignableFrom(eventType)
                || RefreshEvent.class.isAssignableFrom(eventType);
    }

    /**
      * description: 监听刷新消息
      * @param event
      * @return: void
      */
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationReadyEvent) {
            handle((ApplicationReadyEvent) event);
        }
        else if (event instanceof RefreshEvent) {
            handle((RefreshEvent) event);
        }
    }

    public void handle(ApplicationReadyEvent event) {
        this.ready.compareAndSet(false, true);
    }

   /**
    * description: 处理刷新消息
    * @param event
    * @return: void
    */
    public void handle(RefreshEvent event) {
        if (this.ready.get()) { // don't handle events before app is ready
            log.debug("Event received " + event.getEventDesc());
            Set<String> keys = this.refresh.refresh();
            log.info("Refresh keys changed: " + keys);
        }
    }

}

之后调用ContextRefresher 的refresh方法:

    public synchronized Set<String> refresh() {
         //刷新环境变量
        Set<String> keys = refreshEnvironment();
        //刷新scope
        this.scope.refreshAll();
        return keys;
    }

    public synchronized Set<String> refreshEnvironment() {
        //提取原环境变量属性
        Map<String, Object> before = extract(
                this.context.getEnvironment().getPropertySources());
        //创建新容器加载原配置
        addConfigFilesToEnvironment();
        //提取并比较变更的数据
        Set<String> keys = changes(before,
                extract(this.context.getEnvironment().getPropertySources())).keySet();
        //发布变更事件
        this.context.publishEvent(new EnvironmentChangeEvent(this.context, keys));
        return keys;
    }

下面重点关注RefreshScope.refreshAll()方法,发现其内部有一个调用父级的destroy方法,即GenericScope的destroy方法:

    @ManagedOperation(description = "Dispose of the current instance of all beans "
            + "in this scope and force a refresh on next method execution.")
    public void refreshAll() {
        super.destroy();
        this.context.publishEvent(new RefreshScopeRefreshedEvent());
    }

destroy()源码,清空缓存,这这时候之前存在的cache信息就都没有了:

    @Override
    public void destroy() {
        List<Throwable> errors = new ArrayList<Throwable>();
        Collection<BeanLifecycleWrapper> wrappers = this.cache.clear();
        for (BeanLifecycleWrapper wrapper : wrappers) {
            try {
                Lock lock = this.locks.get(wrapper.getName()).writeLock();
                lock.lock();
                try {
                    wrapper.destroy();
                }
                finally {
                    lock.unlock();
                }
            }
            catch (RuntimeException e) {
                errors.add(e);
            }
        }
        if (!errors.isEmpty()) {
            throw wrapIfNecessary(errors.get(0));
        }
        this.errors.clear();
    }

那么缓存被清空后,终于发现导致我们scheduler失效的原因了,那么我们要再次使其生效要怎么做呢?只需要触发GenericScope的get方法,就会帮我们创建新的bean,并加入到cache当中。

五、解决方案
经过上面的分析,我们已经对问题产生的原因有了大致的了解,关键就在于如何在修改配置后,再去调用get方法,使其添加到cache中。实际使用过程中,我们只要再次使用这个bean的对象就可以了。

通过前面的分析我们发现,刷新机制是通过Listener进行监听的,所以这里我们也进行监听,监听到之后进行一次定时方法的调用,代码如下:

package com.mvtech.inbox.infra.utils.scheduler;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * description: 调度
 *  
 * @author: weirx
 * @time: 2021/4/30 11:30
 */
@Slf4j
@RefreshScope
@Component
public class HistoryLogDeleteTask implements ApplicationListener<RefreshScopeRefreshedEvent> {

    @Value("${message.log.timeout}")
    private String timeout;

    @Scheduled(cron = "*/10 * * * * ?")
    public void execute() {
        log.info("thread id:{}", Thread.currentThread().getId());
        this.deleteHistoryLog();
    }

    private void deleteHistoryLog() {
        if (StringUtils.isNotEmpty(timeout)) {
            DateTime dateTime = DateUtil.offsetDay(new Date(), Integer.valueOf(timeout));
            log.info("删除时间:{}", dateTime);
        }
    }

    @Override
    public void onApplicationEvent(RefreshScopeRefreshedEvent event) {
        this.execute();
    }
}

如上所示可以使定时任务bean重新添加到缓存cache当中。过程中调用了GenericScope的get方法,添加缓存。

GenericScope的get

以上就是整体原因的简单分析及解决方案。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,525评论 6 507
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,203评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,862评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,728评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,743评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,590评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,330评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,244评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,693评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,885评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,001评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,723评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,343评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,919评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,042评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,191评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,955评论 2 355

推荐阅读更多精彩内容

  • 动态刷新配置 有时候需要对配置内容做些实时更新,那么spring cloud config是否可以实现呢?肯定是可...
    二月_春风阅读 4,238评论 1 1
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,657评论 18 139
  • spring的bean管理中,每个bean都有对应的scope。在BeanDefinition中就已经指定scop...
    何德何能者阅读 1,876评论 1 2
  • 1.StringBuffer与String的区别 StringBuffer是线程安全的,每次操作字符串,Strin...
    zdd5457阅读 1,000评论 0 5
  • 我是黑夜里大雨纷飞的人啊 1 “又到一年六月,有人笑有人哭,有人欢乐有人忧愁,有人惊喜有人失落,有的觉得收获满满有...
    陌忘宇阅读 8,536评论 28 53