利用 Spring Cloud Config 实现 Shiro 过滤器链动态刷新。

解读

国内主流互联网公司在做微服务改造时,普遍把 Spring Cloud Config + Bus 作为配置中心标配。Shiro 的过滤器链(filterChainDefinitions)默认写死在 shiroFilter 的 Bean 定义里,一旦业务要新增“白名单”或调整鉴权规则,必须 停机→改 yml→打包→重启,在 24h 不断服的场景下完全不可接受。
面试官问“动态刷新”,核心想看四点:

  1. 你能否把 Shiro 的 过滤器链配置 抽成 Spring Cloud Config 远端配置;
  2. 配置变更后,如何利用 @RefreshScope 或 EnvironmentChangeEvent 让 Shiro 重新加载;
  3. 刷新过程必须 无停机、无并发漏洞(旧链已销毁、新链未生效的灰度窗口);
  4. 是否了解 Spring Cloud Bus 消息总线 在多实例场景下的一致性方案。

答好这道题,等于同时展示了“微服务配置中心+安全框架+高可用”的综合能力,是 P7/P8 晋升答辩 的高频考点。

知识点

  1. ShiroFilterFactoryBean 的 setFilterChainDefinitionMap 只在 Spring 容器启动时执行一次,后续无论配置中心怎么变,Bean 都不会自动重建。
  2. Spring Cloud Config Client 通过 @RefreshScope 可以重新初始化 Bean,但 ShiroFilter 是 FilterRegistrationBean 注册到 Servlet 容器的,单纯 @RefreshScope 无法触达。
  3. EnvironmentChangeEvent 或 @ConfigurationProperties 的 rebind 只能刷新普通属性,要让 Shiro 感知,需要 手动重建 ShiroFilterFactoryBean 并重新注册到 ServletContext。
  4. Spring Cloud Bus(Rabbit/Kafka)能在所有实例广播 RefreshRemoteApplicationEvent,保证集群维度配置一致。
  5. 责任链原子切换:借助 SynchronizedList + CopyOnWrite 思想,先构建新链,再用 ServletContext.setAttribute 原子替换,避免并发请求掉进“无链”黑洞。
  6. 国内灰度合规:金融场景要求 配置变更可审计,需把 config-server 的 /actuator/bus-refresh 接口接入 IAM 系统,并记录 谁、何时、改了哪条链。

答案

整体思路:配置外置→事件监听→无停机重建→集群广播。

  1. 在 config-repo 新建 shiro-filter-chain.yml

    shiro:
      filter-chain:
        /api/open/**: anon
        /api/admin/**: authc, roles[admin]
        /api/user/**: authc, perms[user:read]
    

    通过 Spring Cloud Config Server 统一托管。

  2. 客户端引入 spring-cloud-starter-bus-amqp 依赖,开启 @EnableConfigurationProperties。

  3. 定义 ShiroFilterChainProperties 接收远端配置

    @ConfigurationProperties(prefix = "shiro.filter-chain")
    @Component
    @RefreshScope   // 关键
    public class ShiroFilterChainProperties {
        private Map<String, String> chain = new LinkedHashMap<>();
        // getter/setter
    }
    
  4. 自定义 ShiroFilterRefresher 监听 EnvironmentChangeEvent

    @Component
    public class ShiroFilterRefresher implements ApplicationListener<EnvironmentChangeEvent> {
        @Autowired
        private ShiroFilterChainProperties props;
        @Autowired
        private ServletContext servletContext;
        @Autowired
        private DefaultSecurityManager securityManager;
    
        @Override
        public void onApplicationEvent(EnvironmentChangeEvent event) {
            if (event.getKeys().stream().anyMatch(k -> k.contains("shiro.filter-chain"))) {
                rebuildShiroFilter();
            }
        }
    
        private void rebuildShiroFilter() {
            // 1. 新建工厂Bean
            ShiroFilterFactoryBean factory = new ShiroFilterFactoryBean();
            factory.setSecurityManager(securityManager);
            factory.setFilterChainDefinitionMap(props.getChain());
    
            // 2. 获取新链
            AbstractShiroFilter newFilter = null;
            try {
                newFilter = (AbstractShiroFilter) factory.getObject();
            } catch (Exception e) {
                throw new RuntimeException("build filter error", e);
            }
    
            // 3. 原子替换
            servletContext.setAttribute("shiroFilter", newFilter);
            // 4. 广播给集群
            SpringContextHolder.getApplicationContext().publishEvent(new RefreshRemoteApplicationEvent(this, null, null));
        }
    }
    
  5. 在 FilterRegistrationBean 里把 DelegatingFilterProxy 的 targetBeanName 指向 servletContext 属性名(即 shiroFilter),实现 运行时热切换。

  6. 运维侧通过 POST /actuator/bus-refresh 触发,所有节点 3s 内 完成过滤器链更新,零请求丢失。

  7. 配合 配置版本号 与 MD5 指纹,在 Cat/SkyWalking 埋点,实现 灰度回滚 与 审计追踪。

拓展思考

  1. 大规模场景(>500 实例)下,Bus 广播会带来 消息风暴,可改用 Nacos 长轮询 + Sharding 分片刷新,或 Config Server 的 SSE 推送。
  2. 过滤器链 DSL 化:把 “/api/=authc,roles[admin]”** 这种扁平配置升级为 YAML 树形结构,支持 条件表达式(如 headers[version=v2]),再自定义 FilterChainResolver,实现 按灰度号分流。
  3. 与 Gateway 联动:在 Spring Cloud Gateway 侧也维护一份 白名单,通过 GlobalFilter 先挡一层,避免 无效请求 打到业务容器;当 Shiro 链刷新完成后,反向通知 Gateway 刷新内存路由表,实现 端到端一致。
  4. 配置合规:国内银行要求 “配置变更双人复核”,可在 Config Server 加 GitLab MR 流程,合并后自动触发 Jenkins 流水线→灰度 10%→全量,并回写 审计日志到 Elk+Kafka,满足 等保 2.0 的 “安全计算环境” 条款。