当前位置: 首页>后端>正文

闲来无事,贴zuul框架下的一个类的源码

对于初学设计模式的小伙伴,试看下,这里使用了哪些设计模式

package com.netflix.zuul.filters;

import com.netflix.zuul.ZuulFilter;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;

public class FilterRegistry {
    private static final FilterRegistry INSTANCE = new FilterRegistry();
    private final ConcurrentHashMap<String, ZuulFilter> filters = new ConcurrentHashMap();

    public static final FilterRegistry instance() {
        return INSTANCE;
    }

    private FilterRegistry() {
    }

    public ZuulFilter remove(String key) {
        return (ZuulFilter)this.filters.remove(key);
    }

    public ZuulFilter get(String key) {
        return (ZuulFilter)this.filters.get(key);
    }

    public void put(String key, ZuulFilter filter) {
        this.filters.putIfAbsent(key, filter);
    }

    public int size() {
        return this.filters.size();
    }

    public Collection<ZuulFilter> getAllFilters() {
        return this.filters.values();
    }
}
  • 饿汉式单例
  • 工厂方法

自己在使用容器做进程内缓存的时候,当可能遇到并发的场景,考虑ConcurrentHashMap,而不是HashMap。

最后贴出这个类的被调用的写法示例。

闲来无事,贴zuul框架下的一个类的源码,第1张
ConcurrentHashMap的使用示例.png

这里,它把getFilter和putFilter分开实现。
此外,大量使用了ConcurrentHashMap并发集合。

    private final ConcurrentHashMap<String, Long> filterClassLastModified = new ConcurrentHashMap();
    private final ConcurrentHashMap<String, String> filterClassCode = new ConcurrentHashMap();
    private final ConcurrentHashMap<String, String> filterCheck = new ConcurrentHashMap();
    private final ConcurrentHashMap<String, List<ZuulFilter>> hashFiltersByType = new ConcurrentHashMap();
闲来无事,贴zuul框架下的一个类的源码,第2张
getFilter.png

ZuulFilter的实现:filter = FILTER_FACTORY.newInstance(clazz); 它这里有两点值得说。

  • FILTER_FACTORY有一个默认实现的,同时它还支持使用者更换实现。
    static FilterFactory FILTER_FACTORY = new DefaultFilterFactory();
    public void setFilterFactory(FilterFactory factory) {
        FILTER_FACTORY = factory;
    }
  • 使用工厂类的接口,而不是具体的工程类的实现
public interface FilterFactory {
    ZuulFilter newInstance(Class var1) throws Exception;
}

public class DefaultFilterFactory implements FilterFactory {
    public DefaultFilterFactory() {
    }

    public ZuulFilter newInstance(Class clazz) throws InstantiationException, IllegalAccessException {
        return (ZuulFilter)clazz.newInstance();
    }
}

https://www.xamrdz.com/backend/3p71938990.html

相关文章: