Spring Boot教學
Spring Boot是什麼?
Spring Boot簡介
Spring Boot主要目標
Spring Boot快速入門
新項目爲什麼需要Spring Boot?
Spring Boot引導過程
Spring Boot核心和限制
Spring Boot Tomcat部署
Spring Boot優點和缺點
Spring Boot構建系統
Spring Boot入門
Spring Boot代碼結構
Spring Boot安裝
Spring Boot Bean和依賴注入
Spring Boot應用程序開發入門
Spring Boot運行器(Runner)
Spring Boot JSP應用實例
Spring Boot應用程序屬性
Spring Boot將WAR文件部署到Tomcat
Spring Boot日誌
Spring Boot Hello World(Thymeleaf)示例
Spring Boot構建RESTful Web服務
Spring Boot非web應用程序實例
Spring Boot異常處理
Spring Boot @ConfigurationProperties實例
Spring Boot攔截器
Spring Boot SLF4J日誌實例
Spring Boot Servlet過濾器
Spring Boot Ajax實例
Spring Boot Tomcat端口號
Spring Boot文件上傳示例(Ajax和REST)
Spring Boot Rest模板
Spring Boot文件上傳示例
Spring Boot文件處理
Spring Boot服務組件
Spring Boot Thymeleaf示例
Spring Boot使用RESTful Web服務
Spring Boot CORS支持
Spring Boot國際化
Spring Boot調度
Spring Boot啓用HTTPS
Spring Boot Eureka服務器
Spring Boost Eureka服務註冊
Spring Boot Zuul代理服務器和路由
Spring Boot雲配置服務器
Spring Boot雲配置客戶端
Spring Boot Actuator
Spring Boot管理服務器
Spring Boot管理客戶端
Spring Boot啓用Swagger2
Spring Boot創建Docker鏡像
Spring Boot跟蹤微服務日誌
Spring Boot Flyway數據庫
Spring Boot發送電子郵件
Spring Boot Hystrix
Spring Boot Web Socket
Spring Boot批量服務
Spring Boot Apache Kafka
Spring Boot單元測試用例
Spring Boot Rest控制器單元測試
Spring Boot數據庫源(連接數據庫)
Spring Boot保護Web應用程序

Spring Boot批量服務

批處理服務是在單個任務中執行多個命令的過程。 在本章中,將學習如何在Spring Boot應用程序中創建批處理服務。

在開始學習之前,請考慮一個示例,如何將CSV文件內容保存到HSQLDB中。

要創建批處理服務程序,需要在構建配置文件中添加Spring Boot Starter Batch依賴項和HSQLDB依賴項。

Maven用戶可以在pom.xml 文件中添加以下依賴項。

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
   <groupId>org.hsqldb</groupId>
   <artifactId>hsqldb</artifactId>
</dependency>

Gradle用戶可以在build.gradle 文件中添加以下依賴項。

compile("org.springframework.boot:spring-boot-starter-batch")
compile("org.hsqldb:hsqldb")

現在,在資源目錄 - src/main/resources 下添加簡單的CSV數據文件,並將文件命名爲file.csv,如圖所示 -

Max,Su
Da, Lee
Sanfeng, Zhang

接下來,爲HSQLDB編寫一個SQL腳本 - 在資源目(src/main/resources)錄下創建一個文件: request_fail_hystrix_timeout

DROP TABLE USERS IF EXISTS;
CREATE TABLE USERS  (
   user_id BIGINT IDENTITY NOT NULL PRIMARY KEY,
   first_name VARCHAR(20),
   last_name VARCHAR(20)
);

創建一個POJO類,如圖所示 -

package com.yiibai.batchservicedemo;
public class User {
   private String lastName;
   private String firstName;

   public User() {
   }
   public User(String firstName, String lastName) {
      this.firstName = firstName;
      this.lastName = lastName;
   }
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public String getFirstName() {
      return firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }

   @Override
   public String toString() {
      return "firstName: " + firstName + ", lastName: " + lastName;
   }   
}

現在,創建一箇中間處理器,在從CSV文件讀取數據之後和將數據寫入SQL之前執行操作。

package com.yiibai.batchservicedemo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;

public class UserItemProcessor implements ItemProcessor<User, User> {
   private static final Logger log = LoggerFactory.getLogger(UserItemProcessor.class);

   @Override
   public User process(final User user) throws Exception {
      final String firstName = user.getFirstName().toUpperCase();
      final String lastName = user.getLastName().toUpperCase();
      final User transformedPerson = new User(firstName, lastName);

      log.info("Converting (" + user + ") into (" + transformedPerson + ")");
      return transformedPerson;
   }
}

創建一個Batch配置文件,從CSV讀取數據並寫入SQL文件,如下所示。需要在配置類文件中添加[@EnableBatchProcessing](https://github.com/EnableBatchProcessing "@EnableBatchProcessing")註釋。 [@EnableBatchProcessing](https://github.com/EnableBatchProcessing "@EnableBatchProcessing")註釋用於啓用Spring Boot應用程序的批處理操作。

package com.yiibai.batchservicedemo;

import javax.sql.DataSource;
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.launch.support.RunIdIncrementer;
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.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

@Configuration
@EnableBatchProcessing
public class BatchConfiguration {
   @Autowired
   public JobBuilderFactory jobBuilderFactory;

   @Autowired
   public StepBuilderFactory stepBuilderFactory;

   @Autowired
   public DataSource dataSource;

   @Bean
   public FlatFileItemReader<User> reader() {
      FlatFileItemReader<User> reader = new FlatFileItemReader<User>();
      reader.setResource(new ClassPathResource("file.csv"));
      reader.setLineMapper(new DefaultLineMapper<User>() {
         {
            setLineTokenizer(new DelimitedLineTokenizer() {
               {
                  setNames(new String[] { "firstName", "lastName" });
               }
            });
            setFieldSetMapper(new BeanWrapperFieldSetMapper<User>() {
               {
                  setTargetType(User.class);
               }
            });
         }
      });
      return reader;
   }
   @Bean
   public UserItemProcessor processor() {
      return new UserItemProcessor();
   }
   @Bean
   public JdbcBatchItemWriter<User> writer() {
      JdbcBatchItemWriter<User> writer = new JdbcBatchItemWriter<User>();
      writer.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<User>());
      writer.setSql("INSERT INTO USERS (first_name, last_name) VALUES (:firstName, :lastName)");
      writer.setDataSource(dataSource);
      return writer;
   }
   @Bean
   public Job importUserJob(JobCompletionNotificationListener listener) {
      return jobBuilderFactory.get("importUserJob").incrementer(
         new RunIdIncrementer()).listener(listener).flow(step1()).end().build();
   }
   @Bean
   public Step step1() {
      return stepBuilderFactory.get("step1").<User, User>chunk(10).reader(reader()).processor(processor()).writer(writer()).build();
   }
}

reader()方法用於從CSV文件中讀取數據,而writer()方法用於將數據寫入SQL。

接下來,將編寫一個作業完成通知監聽器類 - 用於在作業完成後通知。

package com.yiibai.batchservicedemo;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.listener.JobExecutionListenerSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

@Component
public class JobCompletionNotificationListener extends JobExecutionListenerSupport {
   private static final Logger log = LoggerFactory.getLogger(JobCompletionNotificationListener.class);
   private final JdbcTemplate jdbcTemplate;

   @Autowired
   public JobCompletionNotificationListener(JdbcTemplate jdbcTemplate) {
      this.jdbcTemplate = jdbcTemplate;
   }
   @Override
   public void afterJob(JobExecution jobExecution) {
      if (jobExecution.getStatus() == BatchStatus.COMPLETED) {
         log.info("!!! JOB FINISHED !! It's time to verify the results!!");

         List<User> results = jdbcTemplate.query(
            "SELECT first_name, last_name FROM USERS", new RowMapper<User>() {

            @Override
            public User mapRow(ResultSet rs, int row) throws SQLException {
               return new User(rs.getString(1), rs.getString(2));
            }
         });

         for (User person : results) {
            log.info("Found <" + person + "> in the database.");
         }
      }
   }
}

現在,創建一個可執行的JAR文件,並使用以下Maven或Gradle命令運行Spring Boot應用程序。

對於Maven,使用如下所示的命令 -

mvn clean install

在「BUILD SUCCESS」之後,在target目錄下找到JAR文件。

對於Gradle,可以使用如下所示的命令 -

gradle clean build

在「BUILD SUCCESSFUL」之後,可以在build/libs目錄下找到JAR文件。

使用此處給出的命令運行JAR文件 -

java –jar <JARFILE>

在控制檯窗口中看到作業執行過程輸出。

以下是糾正/補充內容:

應該少了數據庫在application.resources中的配置   提交時間:2019-08-29