多线程实战(多线文件上传)

多线程在springboot中的应用:

问题:多线程不能直接使用注入类,传参可以解决此类问题

/**
 * 多线程文件上传
 *
 * @author zhaokui
 * @version 1.0
 * @date 2018-05-31
 * @return
 */
@RequestMapping(value = "threaduploadFile", method = RequestMethod.POST)
@ResponseBody
public String threaduploadFile(HttpServletRequest request, HttpServletResponse response)
{
    String token=UUID.randomUUID().toString();
    //采用契约模式--盒生产消费者模式
    String str = request.getParameter("file");
    String fileName = request.getParameter("fileName");
    String filetype= "jpg";
    Log.info("文件类型:"+filetype);
    return handleTask.handleRequest(str,token+"."+filetype);


}

正在实现处理的类

package com.itmuch.cloud.study.task;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Service
public class HandleTask {
    private ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 6, 5, TimeUnit.SECONDS, new LinkedBlockingDeque());
    @Autowired
    private  ImageManagerService imageManagerService;

    /**保存文件并上传
     *
     * @param base64Str
     * @param token
     * @return
     */
    public String handleRequest(String base64Str,String token){
        executor.execute(
        new Thread(new MyTask(imageManagerService,base64Str,token)));
        return token;
    }

}
class MyTask implements Runnable{
    private final String base64Str;
    private final String token;
    private final ImageManagerService imageManagerService;
    MyTask(ImageManagerService imageManagerService,String base64Str,String token){
        this.imageManagerService=imageManagerService;
        this.base64Str=base64Str;
        this.token=token;
    }
    @Override
    public void run() {
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bytes = decoder.decodeBuffer(base64Str);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            //上传文件并保存图片
            imageManagerService.saveImages(bytes,token);
            System.out.println(Thread.currentThread().getName()+"---result:"+token);

         }catch (Exception e){
            e.printStackTrace();
         }
    }
}
 
  

业务类

import java.util.Date;

@Service
public class ImageManagerService {
    @Autowired
    private ImageManagerRepository imageManagerRepository;
    @Autowired
    private FastDFSClient fastDFSClient;

    public synchronized void  saveImages(byte[] base64Str,String token){
        String fastDFSpath=fastDFSClient.uploadFile(base64Str,token);
        System.out.println(fastDFSpath);
        ImageManager imageManager =new ImageManager();
        imageManager.setImageName(token);
        imageManager.setUrl(fastDFSpath);
        imageManager.setCreateDate(new Date());
        imageManagerRepository.save(imageManager);
    }
}

此处用到多线程 Single-Threaded-Execution 模式;此处理速度10条/s ;对于并发性要求较高的项目建议不要使用此模式,此模式安全性高,但是会消耗性能;对于并发要求中等可以考虑。

有问题可以加微信:aa544731152 讨论


你可能感兴趣的:(多线程)