完成作业之前的Spring集成关闭

时间:2016-05-24 10:12:47

标签: spring-integration

我已添加到context.xml

<int:gateway id="startJobGateway" default-request-channel="StartJob.request" 
     error-channel="errorChannel" 
     service-interface="spring.integration.gateway.StartJobGateway" 
     default-reply-timeout="10000" default-reply-channel="nullChannel"/>

并在main

public class IntegrationMain extends MBeanExporter implements ApplicationContextAware,
        EmbeddedValueResolverAware {

    public IntegrationMain() {
        super();
        setAutodetect(false);
        setNamingStrategy(this.defaultNamingStrategy);
        setAssembler(this.assembler);
    }

public static void main(String[] args) throws InterruptedException, MalformedObjectNameException, IntrospectionException, InstanceNotFoundException, ReflectionException, MBeanException {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("/context.xml", IntegrationMain.class);

        Map<String, MessageHandlerMetrics> messageHandlers =
                context.getBeansOfType(MessageHandlerMetrics.class);
        for (Map.Entry<String, MessageHandlerMetrics> entry : messageHandlers.entrySet()) {
            String beanName = entry.getKey();
            MessageHandlerMetrics bean = entry.getValue();
            if (handlerInAnonymousWrapper(bean) != null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Skipping " + beanName + " because it wraps another handler");
                }
                continue;
            }
            // If the handler is proxied, we have to extract the target to expose as an MBean.
            // The MetadataMBeanInfoAssembler does not support JDK dynamic proxies.
            MessageHandlerMetrics monitor = (MessageHandlerMetrics) extractTarget(bean);
            handlers.add(monitor);
        }

        Map<String, MessageSourceMetrics> messageSources =
                context.getBeansOfType(MessageSourceMetrics.class);
        for (Map.Entry<String, MessageSourceMetrics> entry : messageSources.entrySet()) {
            // If the source is proxied, we have to extract the target to expose as an MBean.
            // The MetadataMBeanInfoAssembler does not support JDK dynamic proxies.
            MessageSourceMetrics monitor = (MessageSourceMetrics) extractTarget(entry.getValue());
            sources.add(monitor);
        }

        Map<String, MessageChannelMetrics> messageChannels =
                context.getBeansOfType(MessageChannelMetrics.class);
        for (Map.Entry<String, MessageChannelMetrics> entry : messageChannels.entrySet()) {
            // If the channel is proxied, we have to extract the target to expose as an MBean.
            // The MetadataMBeanInfoAssembler does not support JDK dynamic proxies.
            MessageChannelMetrics monitor = (MessageChannelMetrics) extractTarget(entry.getValue());
            channels.add(monitor);
        }
        Map<String, MessageProducer> messageProducers =
                context.getBeansOfType(MessageProducer.class);
        for (Map.Entry<String, MessageProducer> entry : messageProducers.entrySet()) {
            MessageProducer messageProducer = entry.getValue();
            if (messageProducer instanceof Lifecycle) {
                Lifecycle target = (Lifecycle) extractTarget(messageProducer);
                if (!(target instanceof AbstractMessageProducingHandler)) {
                    inboundLifecycleMessageProducers.add(target);
                }
            }
        }

        try {
            registerChannels();
            registerHandlers();
//            registerSources();
//            registerEndpoints();

            if (context.containsBean(IntegrationContextUtils.INTEGRATION_MESSAGE_HISTORY_CONFIGURER_BEAN_NAME)) {
                Object messageHistoryConfigurer = context.getBean(IntegrationContextUtils.INTEGRATION_MESSAGE_HISTORY_CONFIGURER_BEAN_NAME);
/*                if (messageHistoryConfigurer instanceof MessageHistoryConfigurer) {
                    registerBeanInstance(messageHistoryConfigurer,
                            IntegrationContextUtils.INTEGRATION_MESSAGE_HISTORY_CONFIGURER_BEAN_NAME);
                }*/
            }
            if (!context.containsBean(IntegrationManagementConfigurer.MANAGEMENT_CONFIGURER_NAME)) {
                IntegrationManagementConfigurer config = new IntegrationManagementConfigurer();
                config.setDefaultCountsEnabled(true);
                config.setDefaultStatsEnabled(true);
                config.setApplicationContext(context);
                config.setBeanName(IntegrationManagementConfigurer.MANAGEMENT_CONFIGURER_NAME);
                config.afterSingletonsInstantiated();
            }
        }
        catch (RuntimeException e) {
//            unregisterBeans();
            throw e;
        } finally {
            NullChannel activeChannel = context.getBean("nullChannel", NullChannel.class);
            shutdownDeadline = Double.valueOf(activeChannel.getTimeSinceLastSend()).longValue();
            logger.info(shutdownDeadline+ " 1### ");
            stopActiveComponents(3000);
        }
}

    private static void registerChannels() {
        for (MessageChannelMetrics monitor : channels) {
            String name = ((NamedComponent) monitor).getComponentName();
            allChannelsByName.put(name, monitor);
            if (!matches(componentNamePatterns, name)) {
                continue;
            }
            // Only register once...
            if (!channelsByName.containsKey(name)) {
                String beanKey = getChannelBeanKey(name);
                logger.info("Registering MessageChannel " + name);
                if (name != null) {
                    channelsByName.put(name, monitor);
                }
//                registerBeanNameOrInstance(monitor, beanKey);
            }
        }
    }

    private static void registerHandlers() {
        for (MessageHandlerMetrics handler : handlers) {
            MessageHandlerMetrics monitor = enhanceHandlerMonitor(handler);
            String name = monitor.getManagedName();
            allHandlersByName.put(name, monitor);
            if (!matches(componentNamePatterns, name)) {
                continue;
            }
            // Only register once...
            if (!handlersByName.containsKey(name)) {
                String beanKey = getHandlerBeanKey(monitor);
                if (name != null) {
                    handlersByName.put(name, monitor);
                }
//                registerBeanNameOrInstance(monitor, beanKey);
            }
        }
    }
    @ManagedOperation
    public static void stopActiveComponents(long howLong) {
        if (!shuttingDown.compareAndSet(false, true)) {
            logger.error("Shutdown already in process");
            return;
        }

        shutdownDeadline = shutdownDeadline + System.currentTimeMillis() + howLong;
        logger.info(" 2### "+shutdownDeadline);
        try {
            logger.debug("Running shutdown");
            doShutdown();
        }
        catch (Exception e) {
            logger.error("Orderly shutdown failed", e);
        }
    }

    /**
     * Perform orderly shutdown - called or executed from
     * {@link #stopActiveComponents(long)}.
     */
    private static void doShutdown() {
        try {
            orderlyShutdownCapableComponentsBefore();
            stopActiveChannels();
            stopMessageSources();
            stopInboundMessageProducers();
            // Wait any remaining time for messages to quiesce
            long timeLeft = shutdownDeadline - System.currentTimeMillis();
            if (timeLeft > 0) {
                try {
                    Thread.sleep(timeLeft);
                }
                catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    logger.error("Interrupted while waiting for quiesce");
                }
            }
            orderlyShutdownCapableComponentsAfter();
        }
        finally {
            shuttingDown.set(false);
//            context.close();
        }
    }


    protected static final void orderlyShutdownCapableComponentsBefore() {
        logger.debug("Initiating stop OrderlyShutdownCapable components");
        Map<String, OrderlyShutdownCapable> components = context
                .getBeansOfType(OrderlyShutdownCapable.class);
        for (Map.Entry<String, OrderlyShutdownCapable> componentEntry : components.entrySet()) {
            OrderlyShutdownCapable component = componentEntry.getValue();
            int n = component.beforeShutdown();
            if (logger.isInfoEnabled()) {
                logger.info("Initiated stop for component " + component + "; it reported " + n + " active messages");
            }
        }
        logger.debug("Initiated stop OrderlyShutdownCapable components");
    }

    protected static final void orderlyShutdownCapableComponentsAfter() {
        logger.debug("Finalizing stop OrderlyShutdownCapable components");
        Map<String, OrderlyShutdownCapable> components = context
                .getBeansOfType(OrderlyShutdownCapable.class);
        for (Map.Entry<String, OrderlyShutdownCapable> componentEntry : components.entrySet()) {
            OrderlyShutdownCapable component = componentEntry.getValue();
            int n = component.afterShutdown();
            if (logger.isInfoEnabled()) {
                logger.info("Finalized stop for component " + component + "; it reported " + n + " active messages");
            }
        }
//        context.close();
        logger.debug("Finalized stop OrderlyShutdownCapable components");
    }

    @ManagedOperation
    public static void stopActiveChannels() {
        // Stop any "active" channels (JMS etc).
        for (Map.Entry<String, MessageChannelMetrics> entry : allChannelsByName.entrySet()) {
            MessageChannelMetrics metrics = entry.getValue();
            MessageChannel channel = (MessageChannel) metrics;
            if (channel instanceof Lifecycle) {
                if (logger.isInfoEnabled()) {
                    logger.info("Stopping channel " + channel + " status "+((Lifecycle) channel).isRunning());
                }
                ((Lifecycle) channel).stop();
            }
        }
    }

    /**`enter code here`
     * Stops all message sources - may cause interrupts.
     */
    @ManagedOperation
    public static void stopMessageSources() {
        for (Map.Entry<String, MessageSourceMetrics> entry : allSourcesByName.entrySet()) {
            MessageSourceMetrics sourceMetrics = entry.getValue();
            if (sourceMetrics instanceof Lifecycle) {
                if (logger.isInfoEnabled()) {
                    logger.info("Stopping message source " + sourceMetrics +" status "+ ((Lifecycle) sourceMetrics).isRunning());
                }
                ((Lifecycle) sourceMetrics).stop();
            }
            else {
                if (logger.isInfoEnabled()) {
                    logger.info("Message source " + sourceMetrics + " cannot be stopped");
                }
            }
        }
    }

    /**
     * Stops all inbound message producers (that are not {@link OrderlyShutdownCapable})
     * - may cause interrupts.
     */
    @ManagedOperation
    public static void stopInboundMessageProducers() {
        for (Lifecycle producer : inboundLifecycleMessageProducers) {
            if (!(producer instanceof OrderlyShutdownCapable)) {
                if (logger.isInfoEnabled()) {
                    logger.info("Stopping message producer " + producer+ " status "+producer.isRunning());
                }
                producer.stop();
            }
        }
    }
}

但在作业完成之前我仍然会关机。谢谢你的帮助。

0 个答案:

没有答案