Read from database and write to file using camel

随声附和 提交于 2019-12-10 21:36:03

问题


I want to read from the database and write the records to a file using Camel. Below is my code:

import javax.sql.DataSource;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.impl.SimpleRegistry;
import org.apache.commons.dbcp.BasicDataSource;

public class JDBCExampleSimpleRegistry {

    public static void main(String[] args) throws Exception {
        final String url = "jdbc:oracle:thin:@MYSERVER:1521:myDB";
        DataSource dataSource = setupDataSource(url);

        SimpleRegistry reg = new SimpleRegistry() ;
        reg.put("myDataSource",dataSource);

        CamelContext context = new DefaultCamelContext(reg);
        context.addRoutes(new JDBCExampleSimpleRegistry().new MyRouteBuilder());

        context.start();
        Thread.sleep(5000);
        context.stop();
    }

    class MyRouteBuilder extends RouteBuilder {
        public void configure() {
            String dst = "C:/Local Disk E/TestData/Destination/?fileName=output.txt";
            from("direct:myTable")
               .setBody(constant("select * from myTable"))
               .to("jdbc:myDataSource")
                .to("file://" + dst);
        }
    }

    private static DataSource setupDataSource(String connectURI) {
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName("oracle.jdbc.driver.OracleDriver");
        ds.setUsername("sa");
        ds.setPassword("devon1");
        ds.setUrl(connectURI);
        return ds;
    }
}

The above program works fine and CamelContext is elegantly shutdown. However, the target file is not created. What am I doing wrong?

I am a newbie to Apache Camel so appreciate any help. I am using JDK7 with Apache Camel 2.12.1 and is not using Spring.


回答1:


You can take a look at the SQL example: http://camel.apache.org/sql-example.html and then to write to file, is just to send to a file instead of calling the bean as the sql example does.

If you want to use the JDBC component then it doesnt have built-in consumer, so you need to trigger the route using a timer or a quartz scheduler to run the route every X time.



来源:https://stackoverflow.com/questions/19375082/read-from-database-and-write-to-file-using-camel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!