月度归档:2016年11月

BeanNameUrlHandlerMapping与RequestMappingHandlerMapping的区别

1.前者只依赖@Controller(“/abc”)注解进行识别,后者是依赖Controller和ReqestMapping注解进行识别。
2.前者的类对象是由Servlet接口派生,后者是无派生关系的普通类。

@Controller
@RequestMapping("/demo")
public class DemoController {

	@RequestMapping("/findall")
	public String handleList(Model model) {
		logger.info("demo02  handleList");
		List list = demoService.findAll();
		model.addAttribute("results", list);
		return "demo";
	}
}

@Controller("/demo_servlet2")
public class Demo2Servlet extends HttpServlet {	
	@PostConstruct  //init-method="init"
	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		logger.info("Demo2Servlet init start");		
		
		logger.info("Demo2Servlet init end");
	}

	@RequestMapping("/findall")
	public String handleList(Model model) {
		logger.info("demo02  handleList");
		return "demo";
	}

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub

		logger.info("Demo2Servlet service start");

		response.setContentType(CONTENT_TYPE);
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		String result = demoService.getById(1l).getName();
		//Integer.valueOf(result); //测试异常显示页面
		PrintWriter out = response.getWriter();
		out.println("");
		out.println("\n");
		out.println("" + result + "\n");
		out.println("\n");

		out.flush();
		out.close();

		logger.info("Demo2Servlet service end");
	}

	@PreDestroy //destroy-method="destroy"
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		logger.info("Demo2Servlet destroy start");
		
		logger.info("Demo2Servlet destroy end");
	}
	
}

RequestMappingHandlerMapping遍历Controller和RequestMapping注解过程


在AbstractHandlerMethodMapping类中,获取HandlerMethods。

public void afterPropertiesSet() {
        this.initHandlerMethods();
    }

    protected void initHandlerMethods() {
        if(this.logger.isDebugEnabled()) {
            this.logger.debug("Looking for request mappings in application context: " + this.getApplicationContext());
        }
        /*获取所有bean形成列表,后续将会遍历这些bean*/
        String[] beanNames = this.detectHandlerMethodsInAncestorContexts?BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.getApplicationContext(), Object.class):this.getApplicationContext().getBeanNamesForType(Object.class);
        String[] var2 = beanNames;
        int var3 = beanNames.length;

        for(int var4 = 0; var4 < var3; ++var4) {
            String beanName = var2[var4];
            /*通过isHandler函数,检查是否是Controller和RequestMapping注解。它是通过AnnotationUtils和ClassUtils静态类遍历的*/
            if(!beanName.startsWith("scopedTarget.") && this.isHandler(this.getApplicationContext().getType(beanName))) {
                this.detectHandlerMethods(beanName);
            }
        }
        /*获取所有requestMapping对象完成注册的最后一步。*/
        this.handlerMethodsInitialized(this.getHandlerMethods());
    }

在该函数中检查局部变量

在AbstractHandlerMethodMapping的派生类中,即RequestMappingHandlerMapping中,实现了isHandler的类型判断。

在getHandlerMethods中

public Map getHandlerMethods() {
        return Collections.unmodifiableMap(this.handlerMethods);
    }


此外,附加findall代码。

@Controller
@RequestMapping("/demo")
public class DemoController {

	@RequestMapping("/findall")
	public String handleList(Model model) {
		logger.info("demo02  handleList");
		List list = demoService.findAll();
		model.addAttribute("results", list);
		return "demo";
	}
}



@Controller("/demo_servlet2")
public class Demo2Servlet extends HttpServlet {	
	@PostConstruct  //init-method="init"
	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		logger.info("Demo2Servlet init start");		
		
		logger.info("Demo2Servlet init end");
	}

	@RequestMapping("/findall")
	public String handleList(Model model) {
		logger.info("demo02  handleList");
		return "demo";
	}

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub

		logger.info("Demo2Servlet service start");

		response.setContentType(CONTENT_TYPE);
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		String result = demoService.getById(1l).getName();
		//Integer.valueOf(result); //测试异常显示页面
		PrintWriter out = response.getWriter();
		out.println("");
		out.println("\n");
		out.println("" + result + "\n");
		out.println("\n");

		out.flush();
		out.close();

		logger.info("Demo2Servlet service end");
	}

	@PreDestroy //destroy-method="destroy"
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		logger.info("Demo2Servlet destroy start");
		
		logger.info("Demo2Servlet destroy end");
	}
	
}

DispatcherServlet中的URL处理

1.当处理一个URL请求时,将会在DispatcherServlet模块中,循环获取相应的处理Handler。如下图:

2.getHandler的关键函数

protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
        Iterator var2 = this.handlerMappings.iterator();

        HandlerExecutionChain handler;
        do {
            if(!var2.hasNext()) {
                return null;
            }

            HandlerMapping hm = (HandlerMapping)var2.next();
            if(this.logger.isTraceEnabled()) {
                this.logger.trace("Testing handler map [" + hm + "] in DispatcherServlet with name \'" + this.getServletName() + "\'");
            }
            //通过遍历比较,
            handler = hm.getHandler(request);
        } while(handler == null);

        return handler;
    }

3.getHandler中的局部变量






spring注册RestController的关键过程

1.注册RestController时,进入它的反射过程栈信息。

2.registerHandlerMethod时的其中一个变量信息。

3.registerHandlerMethod的具体函数代码

protected void registerHandlerMethod(Object handler, Method method, T mapping) {
        HandlerMethod newHandlerMethod = this.createHandlerMethod(handler, method);
        HandlerMethod oldHandlerMethod = (HandlerMethod)this.handlerMethods.get(mapping);
        if(oldHandlerMethod != null && !oldHandlerMethod.equals(newHandlerMethod)) {
            throw new IllegalStateException("Ambiguous mapping found. Cannot map \'" + newHandlerMethod.getBean() + "\' bean method \n" + newHandlerMethod + "\nto " + mapping + ": There is already \'" + oldHandlerMethod.getBean() + "\' bean method\n" + oldHandlerMethod + " mapped.");
        } else {
            this.handlerMethods.put(mapping, newHandlerMethod);
            if(this.logger.isInfoEnabled()) {
                this.logger.info("Mapped \"" + mapping + "\" onto " + newHandlerMethod);
            }

            Set patterns = this.getMappingPathPatterns(mapping);
            Iterator var7 = patterns.iterator();

            while(var7.hasNext()) {
                String pattern = (String)var7.next();
                if(!this.getPathMatcher().isPattern(pattern)) {
                    this.urlMap.add(pattern, mapping);
                }
            }

        }
    }

3.preInstantiateSingletons的函数是枚举当前的注解定义,把所有注解定义列出来,并进行逐一获取所有注解相关的配置。

public void preInstantiateSingletons() throws BeansException {
        if(this.logger.isDebugEnabled()) {
            this.logger.debug("Pre-instantiating singletons in " + this);
        }

        Map var2 = this.beanDefinitionMap;
        ArrayList beanNames;
        synchronized(this.beanDefinitionMap) {
            beanNames = new ArrayList(this.beanDefinitionNames);
        }

        Iterator var8 = beanNames.iterator();

        while(true) {
            while(true) {
                String beanName;
                RootBeanDefinition bd;
                do {
                    do {
                        do {
                            if(!var8.hasNext()) {
                                return;
                            }

                            beanName = (String)var8.next();
                            bd = this.getMergedLocalBeanDefinition(beanName);
                        } while(bd.isAbstract());
                    } while(!bd.isSingleton());
                } while(bd.isLazyInit());

                if(this.isFactoryBean(beanName)) {
                    final FactoryBean factory = (FactoryBean)this.getBean("&" + beanName);
                    boolean isEagerInit;
                    if(System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                        isEagerInit = ((Boolean)AccessController.doPrivileged(new PrivilegedAction() {
                            public Boolean run() {
                                return Boolean.valueOf(((SmartFactoryBean)factory).isEagerInit());
                            }
                        }, this.getAccessControlContext())).booleanValue();
                    } else {
                        isEagerInit = factory instanceof SmartFactoryBean && ((SmartFactoryBean)factory).isEagerInit();
                    }

                    if(isEagerInit) {
                        this.getBean(beanName);
                    }
                } else {
                    this.getBean(beanName);
                }
            }
        }
    }

spring4.x之HttpMessageConverter

public class WebMvcConfigurationSupport implements ApplicationContextAware, ServletContextAware {
    private static boolean romePresent = ClassUtils.isPresent("com.rometools.rome.feed.WireFeed", WebMvcConfigurationSupport.class.getClassLoader());
    private static final boolean jaxb2Present = ClassUtils.isPresent("javax.xml.bind.Binder", WebMvcConfigurationSupport.class.getClassLoader());
    private static final boolean jackson2Present = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", WebMvcConfigurationSupport.class.getClassLoader()) && ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", WebMvcConfigurationSupport.class.getClassLoader());
    private static final boolean jackson2XmlPresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.xml.XmlMapper", WebMvcConfigurationSupport.class.getClassLoader());
    private static final boolean gsonPresent = ClassUtils.isPresent("com.google.gson.Gson", WebMvcConfigurationSupport.class.getClassLoader());

spring内部已经内置了,feed,json,protobuf的支持,只要在pom.xml的配置文件中添加相应的库支持,即可。



   com.fasterxml.jackson.core
   jackson-core
   ${jackson.version}


   com.fasterxml.jackson.core
   jackson-databind
   ${jackson.version}



 com.google.protobuf
 protobuf-java
 2.5.0


 com.googlecode.protobuf-java-format
 protobuf-java-format
 1.2

Eagle数据安全方案

Apache Eagle:分布式实时 Hadoop 数据安全方案

因为是ebay电商公司的开源,所以它更适合电商平台的使用。

———————————————————-
Eagle Architecture

数据流接入和存储(Data Collection and Storage)

Eagle 提供高度可扩展的编程API,可以支持将任何类型的数据源集成到Eagle的策略执行引擎中。例如,在Eagle HDFS 审计事件(Audit)监控模块中,通过Kafka来实时接收来自Namenode Log4j Appender 或者 Logstash Agent 收集的数据;在Eagle Hive 监控模块中,通过YARN API 收集正在运行Job的Hive 查询日志,并保证比较高的可伸缩性和容错性。

数据实时处理(Data Processing)

流 处理API(Stream Processing API)Eagle 提供独立于物理平台而高度抽象的流处理API,目前默认支持Apache Storm,但是也允许扩展到其他任意流处理引擎,比如Flink 或者 Samza等。该层抽象允许开发者在定义监控数据处理逻辑时,无需在物理执行层绑定任何特定流处理平台,而只需通过复用、拼接和组装例如数据转换、过滤、 外部数据Join等组件,以实现满足需求的DAG(有向无环图),同时,开发者也可以很容易地以编程地方式将业务逻辑流程和Eagle 策略引擎框架集成起来。Eagle框架内部会将描述业务逻辑的DAG编译成底层流处理架构的原生应用,例如Apache Storm Topology 等,从事实现平台的独立。