Spring-Batch-03-Partition

BatchJobConfig.java


package xin.lowang.springbatch.config;

import java.util.Collections;
import java.util.List;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.job.builder.FlowBuilder;
import org.springframework.batch.core.job.flow.Flow;
import org.springframework.batch.core.job.flow.support.SimpleFlow;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.core.partition.support.MultiResourcePartitioner;
import org.springframework.batch.core.partition.support.SimplePartitioner;
import org.springframework.batch.core.partition.support.TaskExecutorPartitionHandler;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider;
import org.springframework.batch.item.database.JdbcBatchItemWriter;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.batch.item.support.ListItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.task.SimpleAsyncTaskExecutor;

import xin.lowang.springbatch.domain.Person;
import xin.lowang.springbatch.processor.PersonItemProcessor;

@Configuration
@EnableBatchProcessing
public class BatchJobConfig {
    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    public DataSource dataSource;

    @Bean
    public FlatFileItemReader<Person> reader() {
        FlatFileItemReader<Person> reader = new FlatFileItemReader<>();
        reader.setResource(new ClassPathResource("sample-data.csv"));
        reader.setLineMapper(new DefaultLineMapper<Person>() {
            {
                setFieldSetMapper(new BeanWrapperFieldSetMapper<Person>() {
                    {
                        setTargetType(Person.class);
                    }
                });
                setLineTokenizer(new DelimitedLineTokenizer() {
                    {
                        setNames(new String[] { "firstName", "lastName" });
                    }
                });
            }
        });
        return reader;
    }

    @Bean
    public PersonItemProcessor processor() {
        return new PersonItemProcessor();
    }

    @Bean
    public JdbcBatchItemWriter<Person> dbWriter() {
        JdbcBatchItemWriter<Person> writer = new JdbcBatchItemWriter<Person>();
        writer.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<Person>());
        writer.setSql("INSERT INTO people (first_name, last_name) VALUES (:firstName, :lastName)");
        writer.setDataSource(dataSource);
        return writer;
    }

    @Bean
    public PrintItemWriter<Person> printWriter() {
        return new PrintItemWriter<Person>() {
            @Override
            public void write(List<? extends Person> items) throws Exception {
                items.stream().forEach(person -> {
                    System.out.println(person.getFirstName() + " is ok");
                });
            }
        };
    }

    @Bean
    public LogItemWriter<Person> logWriter() {
        return new LogItemWriter<Person>() {
            @Override
            public void write(List<? extends Person> items) throws Exception {
                items.stream().forEach(person -> {
                    log.info("person {} is ok", person);
                });
            }
        };
    }

    //定義step和job
    @Bean
    public Step printStep() {
        return stepBuilderFactory.get("printStep").<Person, Person>chunk(2).reader(reader()).processor(processor()).writer(printWriter()).build();
    }

    @Bean
    public Step partitionPrintStep() {
        SimplePartitioner partitioner = new SimplePartitioner();
        MultiResourcePartitioner multiResourcePartitioner = new MultiResourcePartitioner();
        //partitioner.se
        SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();
        taskExecutor.setConcurrencyLimit(4);
        TaskExecutorPartitionHandler taskExecutorPartitionHandler = new TaskExecutorPartitionHandler();
        taskExecutorPartitionHandler.setGridSize(2);
        taskExecutorPartitionHandler.setTaskExecutor(taskExecutor);
        taskExecutorPartitionHandler.setStep(printStep());
        return stepBuilderFactory.get("partitionPrintStep").partitioner("slaveStep", partitioner).partitionHandler(taskExecutorPartitionHandler).build();
    }

    @Bean
    public Step logStep() {
        return stepBuilderFactory.get("logStep").<Person, Person>chunk(2).reader(new ListItemReader<>(Collections.singletonList(new Person("chenghao", "Wang"))))
                .writer(logWriter()).build();
    }

    //@Bean
    public Job importUserJob() {
        Flow flow = new FlowBuilder<SimpleFlow>("asyncFlow").start(logStep()).build();
        return jobBuilderFactory.get("importUserJob").incrementer(new RunIdIncrementer()).flow(printStep()).split(new SimpleAsyncTaskExecutor()).add(flow).build().build();
        //.next(logStep())
        //.end()
        //.build();
    }

    @Bean
    public Job partitionImportUserJob() {
        return jobBuilderFactory.get("importUserJob").incrementer(new RunIdIncrementer()).start(partitionPrintStep()).build();
    }

    public class PrintItemWriter<T> implements ItemWriter<T> {
        @Override
        public void write(List<? extends T> items) throws Exception {
        }
    }

    public class LogItemWriter<T> implements ItemWriter<T> {
        protected final Logger log = LoggerFactory.getLogger(LogItemWriter.class);

        @Override
        public void write(List<? extends T> items) throws Exception {
        }
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子均驶,更是在濱河造成了極大的恐慌戒幔,老刑警劉巖咆槽,帶你破解...
    沈念sama閱讀 217,406評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件速那,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡懈涛,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門泳猬,熙熙樓的掌柜王于貴愁眉苦臉地迎上來批钠,“玉大人,你說我怎么就攤上這事得封÷裥模” “怎么了?”我有些...
    開封第一講書人閱讀 163,711評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵忙上,是天一觀的道長拷呆。 經(jīng)常有香客問我,道長疫粥,這世上最難降的妖魔是什么茬斧? 我笑而不...
    開封第一講書人閱讀 58,380評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮梗逮,結(jié)果婚禮上项秉,老公的妹妹穿的比我還像新娘。我一直安慰自己慷彤,他們只是感情好娄蔼,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,432評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著底哗,像睡著了一般岁诉。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上跋选,一...
    開封第一講書人閱讀 51,301評(píng)論 1 301
  • 那天涕癣,我揣著相機(jī)與錄音,去河邊找鬼野建。 笑死属划,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的候生。 我是一名探鬼主播同眯,決...
    沈念sama閱讀 40,145評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼唯鸭!你這毒婦竟也來了须蜗?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,008評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤目溉,失蹤者是張志新(化名)和其女友劉穎明肮,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體缭付,經(jīng)...
    沈念sama閱讀 45,443評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡柿估,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,649評(píng)論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了陷猫。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片秫舌。...
    茶點(diǎn)故事閱讀 39,795評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖绣檬,靈堂內(nèi)的尸體忽然破棺而出足陨,到底是詐尸還是另有隱情,我是刑警寧澤娇未,帶...
    沈念sama閱讀 35,501評(píng)論 5 345
  • 正文 年R本政府宣布墨缘,位于F島的核電站,受9級(jí)特大地震影響零抬,放射性物質(zhì)發(fā)生泄漏镊讼。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,119評(píng)論 3 328
  • 文/蒙蒙 一平夜、第九天 我趴在偏房一處隱蔽的房頂上張望狠毯。 院中可真熱鬧,春花似錦褥芒、人聲如沸嚼松。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽献酗。三九已至,卻和暖如春坷牛,著一層夾襖步出監(jiān)牢的瞬間罕偎,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評(píng)論 1 269
  • 我被黑心中介騙來泰國打工京闰, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留颜及,地道東北人甩苛。 一個(gè)月前我還...
    沈念sama閱讀 47,899評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像俏站,于是被迫代替她去往敵國和親讯蒲。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,724評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容