camel 将 csv 转换 json 同时发起post请求

通过 camel 操作

package com.use.file2;

import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.dataformat.bindy.csv.BindyCsvDataFormat;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.model.dataformat.JsonLibrary;
import org.apache.log4j.PropertyConfigurator;

public class HttpToCsvWithCamel {
    public static void main(String[] args) throws Exception {
        // 日志
        String path = Thread.currentThread().getContextClassLoader().getResource("./").getPath();
        PropertyConfigurator.configure(path + "log4j2.properties");
        PropertyConfigurator.configureAndWatch(path + "log4j2.properties", 1000);

        // 这是camel上下文对象,整个路由的驱动全靠它了。
        CamelContext context = new DefaultCamelContext();
        //  构建路由
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                //  绑定 对应的实体类转换格式
                BindyCsvDataFormat bindy = new BindyCsvDataFormat(Message2.class);
                bindy.setLocale("default");
              
                from("file:d://data/inbox?fileName=message2.csv&noop=true")
                   // 解析 xml
                    .unmarshal(bindy)
                   //  解析log输出
                    .log("${body}")
                    // 封装
                    .marshal()
                    // 转换 json
                    .json(JsonLibrary.Jackson)
                    // 封装json -- log输出
                    .log("${body}")
                    // 为了测试是否能获取 csv 文件
                    // .to("file:d://data/inbox?fileName=message1.csv&noop=true");
                    // post 格式请求
                    .setHeader(Exchange.HTTP_METHOD, constant("POST"))
                    // 请求地址
                    .to("http://localhost:8080/convertJson");
            }
        });

        // 启动route
        context.start();
        //  主线程休息
        Thread.sleep(10000);
         // 
        context.stop();
    }
}
@CsvRecord(separator = ",")
public class Message2 {
    @DataField(pos = 1)
    private String name;

    @DataField(pos = 2)
    private Integer code;

    @DataField(pos = 3)
    private String address;
--- Getter Setter ---

你可能感兴趣的:(camel 将 csv 转换 json 同时发起post请求)