首页 > 代码库 > Camel添加路由过程

Camel添加路由过程

    Camel添加路由一般情况下是调用CamelContext的addRoutes(RoutesBuilder builder)方法实现的,下面我们看看该方法是如何实现路由的添加的:

public void addRoutes(RoutesBuilder builder) throws Exception {
	//调用RouteBuilder的addRoutesToCamelContext方法,并将CamelContext作为参数传递进去
    builder.addRoutesToCamelContext(this);
}

下面是addRoutesToCamelContext方法源码:

public void addRoutesToCamelContext(CamelContext context) throws Exception {
    configureRoutes((ModelCamelContext)context);
    populateRoutes();
}

这里调用了两个方法,我们先看configureRoutes方法,该方法的工作是配置路由:

public RoutesDefinition configureRoutes(ModelCamelContext context) throws Exception {
    setContext(context);
    checkInitialized();
    routeCollection.setCamelContext(context);
    return routeCollection;
}

这其中最重要的是checkInitialized方法,其它的都很简单,下面就看看checkInitialized方法:

protected void checkInitialized() throws Exception {
    if (initialized.compareAndSet(false, true)) {
        ModelCamelContext camelContext = getContext();
        if (camelContext.getErrorHandlerBuilder() != null) {
            setErrorHandlerBuilder(camelContext.getErrorHandlerBuilder());
        }
        configure();
        for (RouteDefinition route : getRouteCollection().getRoutes()) {
            route.markPrepared();
        }
    }
}

该方法首先在检查有没有初始化过,如果是第一次执行,肯定是没有进行初始化的,如果会执行configure()方法,而这个方法就是我们在创建RouteBuilder对象时要实现的方法,在该方法中完成了RouteDefinition的配置与创建。configure()方法执行完成后遍历所有路由标记已预处理过了。

下面我们去看看populateRoutes()方法,该方法中就是真正将路由定义添加到CamelContext中的操作:

protected void populateRoutes() throws Exception {
    ModelCamelContext camelContext = getContext();
    if (camelContext == null) {
        throw new IllegalArgumentException("CamelContext has not been injected!");
    }
    getRouteCollection().setCamelContext(camelContext);
    //将所有路由定义取出,并且添加到CamelContext中
    camelContext.addRouteDefinitions(getRouteCollection().getRoutes());
}

下面是CamelContext的addRouteDefinitions源码:

public synchronized void addRouteDefinitions(Collection<RouteDefinition> routeDefinitions) throws Exception {
    //遍历所有路由定义
    for (RouteDefinition routeDefinition : routeDefinitions) {
    	//如果路由定义已经存在则移除原有定义
        removeRouteDefinition(routeDefinition);
    }
    //将所有路由定义添加到路由定义集合中
    this.routeDefinitions.addAll(routeDefinitions);
    //判断是否要启动路由
    if (shouldStartRoutes()) {
        startRouteDefinitions(routeDefinitions);
    }
}

在shouldStartRoutes方法中,如果CamelContext已启动并且不是在启动过程中则返回true,所以在CamelContext启动之后再添加新的路由定义该路由定义是会自动启动的。

添加路由与跌幅的配置创建就讲完了,下面就是最重要的:路由定义的执行过程,即路由定义的启动过程,这个下回讲解......

Camel添加路由过程