今天想写一下ApacheCamel的错误处理。Camel的错误处理和Java的错误处理有很大不同。在Java中我们通过try,catch捕获异常以后处理异常。但是,Camel中我们是先定义路由,然后程序一次性读入所有路由,在路由被调用时才可能会发生异常,而且当发生异常时也要保证后面的路由还可以被正确调用,而不能停止。
Camel中有错误处理器,异常策略的概念。错误处理器真对于所有异常,异常策略针对于指定异常。他们都可以设定返还策略(返还回数,时间间隔,日志级别…)等。
下面上代码,这个程序我是根据以前写的JDBC组件程序改的。
程序结构
JDBCLogErrorProcess.java
package com.camel.jdbc.process;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.log4j.Logger;
public class JDBCLogErrorProcess implements Processor{
public static final Logger logger = Logger.getLogger(JDBCLogErrorProcess.class);
public void process(Exchange exchange) throws Exception {
Exception e = exchange.getProperty(Exchange.EXCEPTION_CAUGHT,Exception.class);
if(null != e){
logger.info("++++++++++++++++++++++++++++++++++++++");
logger.info("[JDBC路由][ERROR]errorMSG=" + e.getMessage());
logger.info("++++++++++++++++++++++++++++++++++++++");
}else{
logger.info("++++++++++++++++++++++++++++++++++++++");
logger.info("[JDBC路由][TO]exchangeId=" + exchange.getExchangeId() + "|fromRouteId=" +exchange.getFromRouteId());
}
}
}
JDBCLogFromProcess.java
package com.camel.jdbc.process;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.log4j.Logger;
public class JDBCLogFromProcess implements Processor{
public static final Logger logger = Logger.getLogger(JDBCLogFromProcess.class);
public void process(Exchange exchange) throws Exception {
logger.info("[JDBC路由][FROM]exchangeId=" + exchange.getExchangeId() + "|fromRouteId=" +exchange.getFromRouteId());
}
}
JDBCLogToProcess.java
package com.camel.jdbc.process;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.log4j.Logger;
public class JDBCLogToProcess implements Processor{
public static final Logger logger = Logger.getLogger(JDBCLogToProcess.class);
public void process(Exchange exchange) throws Exception {
logger.info("[JDBC路由][TO]exchangeId=" + exchange.getExchangeId() + "|fromRouteId=" +exchange.getFromRouteId());
}
}
JDBCRoute.java
package com.camel.jdbc.route;
import org.apache.camel.LoggingLevel;
import org.apache.camel.builder.RouteBuilder;
import org.apache.log4j.Logger;
import com.camel.jdbc.process.JDBCLogFromProcess;
import com.camel.jdbc.process.JDBCLogToProcess;
import com.camel.jdbc.process.JDBCLogErrorProcess;
public class JDBCRoute extends RouteBuilder {
Logger logger = Logger.getLogger(JDBCRoute.class);
public void configure() {
try {
// 全局错误处理器为默认错误处理器
errorHandler(defaultErrorHandler());
// 当路由中发生异常时处理
onException(Exception.class) // 捕获所有异常
.handled(true) // 路由停止将错误信息返回给最初的消费者
.maximumRedeliveries(2) // 路由尝试返还2次
.redeliveryDelay(1000) // 每次返还间隔1秒
.retryAttemptedLogLevel(LoggingLevel.INFO) // 返还时日志级别设为INFO
.retriesExhaustedLogLevel(LoggingLevel.INFO) // 返还失败时日志级别设为INFO
.process(new JDBCLogErrorProcess()); // 最终异常发生时处理
// 定时任务,每60秒执行一次
// from为路由入口
from("timer://queryAward?period=60s")
.process(new JDBCLogFromProcess()) // 输出路由From日志
.bean(sql.class, "getAll") // 设定SQL
.to("jdbc:DataSource") // 取数据库结果
.split(body())
.setBody(simple("insert into ordertb values('${body[orderId]}','${body[goodsId]}','${body[name]}')"))
.to("jdbc:DataSource")
.process(new JDBCLogToProcess()); // 输出路由To日志
} catch (Exception e) {
e.printStackTrace();
}
}
}
sql.java
package com.camel.jdbc.route;
public class sql {
public String getAll(){
return "select * from orders";
}
}
CamelJDBCServer.java
package com.camel.jdbc.server;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.impl.SimpleRegistry;
import org.apache.camel.model.ModelCamelContext;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.log4j.Logger;
import com.camel.jdbc.route.JDBCRoute;
public class CamelJDBCServer {
public static final Logger logger = Logger.getLogger(CamelJDBCServer.class);
public static void main(String[] args) {
final String url = "jdbc:mysql://127.0.0.1:3306/test";
BasicDataSource basicDataSource = new BasicDataSource();
basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
basicDataSource.setUsername("root");
basicDataSource.setPassword("root");
basicDataSource.setUrl(url);
SimpleRegistry simpleregistry = new SimpleRegistry();
simpleregistry.put("DataSource", basicDataSource);
try {
ModelCamelContext camelContext = new DefaultCamelContext(simpleregistry);
camelContext.start();
camelContext.addRoutes(new JDBCRoute());
// 没有具体业务意义的代码,只是为了保证主线程不退出
synchronized (CamelJDBCServer.class) {
CamelJDBCServer.class.wait();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
log4j.properties
### \u8BBE\u7F6E###
log4j.rootLogger = info,stdout,D,E
### \u8F93\u51FA\u4FE1\u606F\u5230\u63A7\u5236\u62AC ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
### \u8F93\u51FADEBUG \u7EA7\u522B\u4EE5\u4E0A\u7684\u65E5\u5FD7\u5230=D://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = E://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### \u8F93\u51FAERROR \u7EA7\u522B\u4EE5\u4E0A\u7684\u65E5\u5FD7\u5230=D://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E://logs/error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com</groupId>
<artifactId>camel-example-JDBC</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- 数据源 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<!-- spring整合mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.0.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core</artifactId>
<version>2.17.5</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-spring</artifactId>
<version>2.17.5</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-jetty</artifactId>
<version>2.17.5</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-jdbc</artifactId>
<version>2.17.5</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180130</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
</dependency>
</dependencies>
</project>
经测试运行结果符合预期。
版权声明:本文为weixin_41368339原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。