使用异步线程入数据库(一)

拜拜、爱过 提交于 2020-08-13 09:08:46
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);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!