Thursday, May 23, 2013

Spring, Camel consumer shutdown hack


import java.lang.reflect.Field;
import java.util.List;

import org.apache.camel.Consumer;
import org.apache.camel.spring.remoting.CamelServiceExporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.SmartLifecycle;

import amqp.spring.camel.component.SpringAMQPConsumer;

/**
 * Bean to help shutdown Camel beans that do not have a doStop() method that does what's needed to shut them down
 *
 */
public class AmqpConsumerShutdownBean implements SmartLifecycle {
@Autowired(required = false)
List<CamelServiceExporter> camelExports;
private boolean running = false;
public AmqpConsumerShutdownBean() {
}

@Override
public void start() {
this.running = true;
}

@Override
public void stop() {
if (this.camelExports == null) {
return;
}
for (CamelServiceExporter bean : this.camelExports) {
Field f = null;
try {
f = bean.getClass().getDeclaredField("consumer");
f.setAccessible(true);
Consumer consumer = (Consumer)f.get(bean);
consumer.getEndpoint();
if (consumer instanceof SpringAMQPConsumer) {
consumer.getEndpoint().stop();
((SpringAMQPConsumer) consumer).doShutdown();
f.set(bean, null);
bean.destroy();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (f != null) {
f.setAccessible(false);
}
}
}
this.running = false;
}

@Override
public boolean isRunning() {
return this.running;
}


@Override
public int getPhase() {
return 1;
}

@Override
public boolean isAutoStartup() {
return true;
}

@Override
public void stop(Runnable callback) {
if (this.isRunning()) {
this.stop();
}
callback.run();
}


}

No comments:

Post a Comment