使用异步线程入数据库(一)
package com.huawei.controller; import com.huawei.pojo.Teacher; import com.huawei.service.TeacherService; import com.huawei.thread.TeacherThreadTask; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @Author jose * date 2020 */ @RestController @RequestMapping("/testController") public class TestController { @Autowired private TeacherService teacherService; /** * 调用异步线程入库 */ @RequestMapping("/testThread") public void testThread(@RequestBody Teacher teacher){ ExecutorService threadPool = Executors.newFixedThreadPool(20); TeacherThreadTask teacherThreadTask = new TeacherThreadTask(teacher,teacherService); threadPool.execute(teacherThreadTask); } }
二.线程类
package com.huawei.thread; import com.huawei.pojo.Teacher; import com.huawei.service.TeacherService; /** * @Author jose * date 2020 */ public class TeacherThreadTask implements Runnable { private Teacher teacher; private TeacherService teacherService; public TeacherThreadTask( Teacher teacher,TeacherService teacherService){ this.teacher=teacher; this.teacherService=teacherService; } @Override public void run() { teacherService.insert(teacher); } }
三.接口
package com.huawei.service; import com.huawei.pojo.Teacher; /** * @Author jose * date 2020 */ public interface TeacherService { void insert (Teacher teacher); }
四.实现类
package com.huawei.service.impl; import com.huawei.mapper.TeacherMapper; import com.huawei.pojo.Teacher; import com.huawei.service.TeacherService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @Author jose * date 2020 */ @Service public class TeacherImpl implements TeacherService { @Autowired private TeacherMapper teacherMapper; @Override public void insert(Teacher teacher) { teacherMapper.insert(teacher); } }