Nacos配置中心,Filter中动态获取参数

需求描述:

最近需要实现一个功能,token验证参数可以动态配置化,即在不关闭应用的前提下实现token验证功能的关闭和开启功能,于是想到了使用分布式配置中心Nacos,如何在Filter中获取Nacos配置中心的参数?
在功能修改过程中出现了各种问题,如果不想关注中间过程可以采用最终版本,可以实现Filter中动态获取参数的功能。

原配置参数如下

token:
    enable: true
    urlPatterns: /*
    excluded:
      paths: /list1,/test1,/test2

原代码

Token配置类

@Configuration
public class TokenConfig {

    public static final String TOKEN_ID = "localUUID";
    public static final String PLAN_DETAIL_UUID = "planDetailUuid";
    public static final String TOKEN_EXCLUDED_PATHS = "TOKEN_EXCLUDED_PATHS";
    public static final String TOKEN_ENABLE = "TOKEN_ENABLE";
    public static final String TOKEN_NAME = "MOBILE_TOKEN";

    @Value("${token.urlPatterns}")
    private String urlPatterns;

    @Value("${token.excluded.paths}")
    private String excludedPaths;

    @Value("${token.enable}")
    private String tokenEnable;

    @Autowired
    private TokenLoginHelper tokenLoginHelper;

    @Bean
    public FilterRegistrationBean tokenFilterRegistration() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setDispatcherTypes(DispatcherType.REQUEST);
        registrationBean.setFilter(new TokenFilter(tokenLoginHelper));
        registrationBean.addUrlPatterns(StringUtils.split(urlPatterns, ",") == null ? new String[]{urlPatterns} : StringUtils.split(urlPatterns, ","));
        registrationBean.setName("TokenFilter");
        registrationBean.setOrder(9999);
        Map<String, Object> initParameters = new HashMap<>();
        initParameters.put(TokenConfig.TOKEN_EXCLUDED_PATHS, excludedPaths);
        initParameters.put(TokenConfig.TOKEN_ENABLE, tokenEnable);
        registrationBean.setInitParameters(initParameters);
        return registrationBean;
    }
}

TokenFilter过滤器如下

/**
 * h5二维码token验证
 */
public class TokenFilter extends HttpServlet implements Filter {

    private TokenLoginHelper tokenLoginHelper;

    private static Logger logger = LoggerFactory.getLogger(TokenFilter.class);

    private static final AntPathMatcher antPathMatcher = new AntPathMatcher();

    private String excludedPaths;

    private String tokenEnable;

    public TokenFilter(TokenLoginHelper tokenLoginHelper) {
        this.tokenLoginHelper = tokenLoginHelper;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        tokenEnable = filterConfig.getInitParameter(TokenConfig.TOKEN_ENABLE);
        excludedPaths = filterConfig.getInitParameter(TokenConfig.TOKEN_EXCLUDED_PATHS);
        logger.info("TokenFilter init.");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        // make url
        String servletPath = req.getServletPath();

        if (!"true".equals(tokenEnable)) {
            chain.doFilter(request, response);
            return;
        }

        // excluded path check
        if (excludedPaths != null && excludedPaths.trim().length() > 0) {
            for (String excludedPath : excludedPaths.split(",")) {
                String uriPattern = excludedPath.trim();
                // 支持ANT表达式
                if (antPathMatcher.match(uriPattern, servletPath)) {
                    // excluded path, allow
                    chain.doFilter(request, response);
                    return;
                }
            }
        }

        // mobile token filter
        boolean flag = tokenLoginHelper.tokenCheck(req);
        if (!flag) {
            // response
            res.setStatus(HttpServletResponse.SC_OK);
            res.setContentType("application/json;charset=UTF-8");
            res.getWriter().println("{\"code\":501, \"msg\":\"未知错误\"}");
            return;
        }

        // already login, allow
        chain.doFilter(request, response);
        return;
    }


}

第一版修改

按照官网Nacos的用法

1.对 TokenConfig 进行改造,增加@RefreshScope注解,可以对@Value(${...})参数实时刷新

@Configuration
@RefreshScope
public class TokenConfig {
    ...

2.引入相关的依赖

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
            <version>2.1.0.RELEASE</version>
        </dependency>

3.修改bootstrap.yml文件

spring:
  application:
    name: eval-zjiaomobile
  cloud:
    nacos:
      config:
        server-addr: 127.0.0.1:8848
        file-extension: yaml
        group: zjiao_group

但是发现TokenConfig上增加@RefreshScope注解之后,FilterRegistrationBean注入失效,过滤器不生效

    @Bean
    public FilterRegistrationBean tokenFilterRegistration() {
        ...

如果不使用@RefreshScope注解,Filter过滤器正常工作,但是没有实时刷新效果。

第二版修改

分为两个类来处理,TokenConfig类独立实时刷新,而FilterRegistrationBean在其他类中注入,保证两个过程不冲突

@Configuration
@RefreshScope
public class TokenConfig {

    public static final String TOKEN_ID = "localUUID";
    public static final String PLAN_DETAIL_UUID = "planDetailUuid";
    public static final String TOKEN_EXCLUDED_PATHS = "TOKEN_EXCLUDED_PATHS";
    public static final String TOKEN_ENABLE = "TOKEN_ENABLE";
    public static final String TOKEN_NAME = "MOBILE_TOKEN";

    @Value("${token.urlPatterns}")
    private String urlPatterns;

    @Value("${token.excluded.paths}")
    private String excludedPaths;

    @Value("${token.enable}")
    private String tokenEnable;

    public String getUrlPatterns() {
        return urlPatterns;
    }

    public String getExcludedPaths() {
        return excludedPaths;
    }

    public String getTokenEnable() {
        return tokenEnable;
    }
}

TokenFilterBeanConfig 分离出来,只做FilterBean的配置

@Configuration
public class TokenFilterBeanConfig {

    @Autowired
    private TokenLoginHelper tokenLoginHelper;

    @Autowired
    private TokenConfig tokenConfig;

    @Bean
    public FilterRegistrationBean tokenFilterRegistration() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setDispatcherTypes(DispatcherType.REQUEST);
        registrationBean.setFilter(new TokenFilter(tokenLoginHelper));
        registrationBean.addUrlPatterns(StringUtils.split(tokenConfig.getUrlPatterns(), ",") == null ?
                new String[]{tokenConfig.getUrlPatterns()} : StringUtils.split(tokenConfig.getUrlPatterns(), ","));
        registrationBean.setName("TokenFilter");
        registrationBean.setOrder(9999);
        Map<String, Object> initParameters = new HashMap<>();
        initParameters.put(TokenFilterBeanConfig.TOKEN_EXCLUDED_PATHS, tokenConfig.getExcludedPaths());
        initParameters.put(TokenFilterBeanConfig.TOKEN_ENABLE, tokenConfig.getTokenEnable());
        registrationBean.setInitParameters(initParameters);
        return registrationBean;
    }
}

发现Filter中永远只会使用第一次初始化的FilterRegistrationBean,参数不会实时更新,因为Bean只会初始化一次。

第三版修改

Filter过滤器中进行实时刷新,取到的值都是null,部分代码如下

@Component
@RefreshScope
public class TokenFilter extends HttpServlet implements Filter {
    
    @Value("${token.excluded.paths}")
    private String excludedPaths;

    @Value("${token.enable}")
    private String tokenEnable;
    ...

最终版本(问题解决)

1.必须在每次访问接口的时候,动态的去获取${token.enable}的值,所以必须是在FilterdoFilter方法中去获取。
2.通过Environment对象获取token.enable的值
3.实现EnvironmentAware接口,可以在Spring初始化过程中获取到Environment对象

TokenConfig 实时刷新参数不变

@Configuration
@RefreshScope
public class TokenConfig {
    ...
    @Value("${token.excluded.paths}")
    private String excludedPaths;

    @Value("${token.enable}")
    private String tokenEnable;
    ...

Filter使用Environment对象获取token.enable的值,这一点是受官网测试代码的启发String userName = applicationContext.getEnvironment().getProperty("user.name");

最终代码如下:

@Component
public class TokenFilter extends HttpServlet implements Filter, EnvironmentAware {

    private static Environment environment;

    private TokenLoginHelper tokenLoginHelper;

    private static Logger logger = LoggerFactory.getLogger(TokenFilter.class);

    private static final AntPathMatcher antPathMatcher = new AntPathMatcher();

    public TokenFilter(TokenLoginHelper tokenLoginHelper) {
        this.tokenLoginHelper = tokenLoginHelper;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("TokenFilter init.");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        // make url
        String servletPath = req.getServletPath();

        String tokenEnable =  environment.getProperty("token.enable");
        String excludedPaths =  environment.getProperty("token.excluded.paths");

        System.out.println("tokenEnable>>>>>>>>>>>>>>>>>>>>>"+tokenEnable);
        System.out.println("excludedPaths>>>>>>>>>>>>>>>>>>>>>"+excludedPaths);

        if (!"true".equals(tokenEnable)) {
            chain.doFilter(request, response);
            return;
        }

        // excluded path check
        if (excludedPaths != null && excludedPaths.trim().length() > 0) {
            for (String excludedPath : excludedPaths.split(",")) {
                String uriPattern = excludedPath.trim();
                // 支持ANT表达式
                if (antPathMatcher.match(uriPattern, servletPath)) {
                    // excluded path, allow
                    chain.doFilter(request, response);
                    return;
                }
            }
        }

        // mobile token filter
        boolean flag = tokenLoginHelper.tokenCheck(req);
        if (!flag) {
            // response
            res.setStatus(HttpServletResponse.SC_OK);
            res.setContentType("application/json;charset=UTF-8");
            res.getWriter().println("{\"code\":501, \"msg\":\"无权限访问\"}");
            return;
        }

        // already login, allow
        chain.doFilter(request, response);
        return;
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}

测试截图

filter中打印信息
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zlV29oYm-1577155810558)(C:\Users\xiewenfeng\AppData\Roaming\Typora\typora-user-images\1577154398300.png)]
前端效果
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aE8tE9pf-1577155810560)(C:\Users\xiewenfeng\AppData\Roaming\Typora\typora-user-images\1577155536455.png)]

修改nacos中的配置信息,false写错了不好意思
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7W7OUvgR-1577155810561)(C:\Users\xiewenfeng\AppData\Roaming\Typora\typora-user-images\1577154457193.png)]

修改之后

控制台实时打印,因为nacos采用的是一种特殊的push机制,所以只需要修改配置信息,就会实时推送到客户端。
在这里插入图片描述
再访问该接口
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值