@Data
public class User {
private String id;
@ExcelProperty(index = 0)
private String userName;
@ExcelProperty(index = 1)
private String sex;
@ExcelProperty(index = 2)
private Integer age;
}
@RestController
public class DemoController {
@Resource
private UserService userService;
@PostMapping("upload")
@ResponseBody
public boolean importData(MultipartFile file) {
return userService.importData(file);
}
}
public interface UserService extends IService<User> {
boolean importData(MultipartFile file);
}
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Resource
private UserMapper userMapper;
@Transactional(rollbackFor = Exception.class)
@Override
public boolean importData(MultipartFile file) {
List<Runnable> threads = new ArrayList<>();
for (int i = 0; i < 6; i++) {
int num = i;
threads.add(() -> {
try {
EasyExcel.read(file.getInputStream(), User.class, new UserDataListener(userMapper)).sheet(num).doRead();
} catch (IOException e) {
e.printStackTrace();
}
});
}
ExecutorService threadPool = Executors.newFixedThreadPool(6);
for (Runnable thread : threads) {
threadPool.execute(thread);
}
threadPool.shutdown();
return true;
}
}
public class UserDataListener implements ReadListener<User> {
private static final int BATCH_COUNT = 100;
private List<User> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
private UserMapper userMapper;
public UserDataListener(UserMapper userMapper) {
this.userMapper = userMapper;
}
@Override
public void invoke(User data, AnalysisContext context) {
cachedDataList.add(data);
if (cachedDataList.size() >= BATCH_COUNT) {
saveData();
cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
String threadName = Thread.currentThread().getName();
System.out.println(threadName);
saveData();
}
private void saveData() {
userMapper.myBatchSave(cachedDataList);
}
}
public interface UserMapper extends BaseMapper<User> {
int myBatchSave(@Param("users") List<User> users);
}
<insert id="myBatchSave" parameterType="java.util.List">
insert into tb_user(user_name, sex, age) values
<foreach collection="users" item="user" separator=",">
(#{user.userName}, #{user.sex}, #{user.age})
</foreach>
</insert>