zoukankan      html  css  js  c++  java
  • 简易多线程任务 往数据库插数据

    threadController  类:

    package com.threads.threadPoolInsertData;
    
    import java.io.IOException;
    import java.sql.Timestamp;
    import java.util.Date;
    import java.util.UUID;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import com.alibaba.fastjson.JSONObject;
    
    @Controller
    public class threadController {
    
        @Autowired
        private threadService threadService;
        /**
         * 接收params参数
         * @param request
         * @param response
         * @throws IOException
         */
        @RequestMapping("/thread/requestData.do") 
        public void  requestData(HttpServletRequest request,HttpServletResponse response) throws IOException {
            request.setCharacterEncoding("UTF-8");
            response.setContentType("text/plain; charset=UTF-8");
            String stFjId = UUID.randomUUID().toString();
            String url = request.getParameter("url");
            String stApplyId = "000000000000001";
            String fjName = request.getParameter("fjName"); 
    //        Date date = new Date();
    //        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //        String time = format.format(date).toString();
            Timestamp  saveTime=new Timestamp(new Date().getTime());
            JSONObject json = new  JSONObject();
            json.put("stFjId", stFjId);
            json.put("url", url);
            json.put("stApplyId", stApplyId);
            json.put("fjName", fjName);
            json.put("time", saveTime);
            System.out.println("requestData--->"+json);
            threadService.insertData(json);
            
        }
        
        /**
         * 接收json参数
         * @param request
         * @param response
         * @throws IOException
         */
        @RequestMapping("/thread/requestData1.do")
        public void  requestData1(HttpServletRequest request,HttpServletResponse response) throws IOException{
            String data = threadService.getRequestPostStr(request);
            JSONObject json = JSONObject.parseObject(data);
            String stFjId = UUID.randomUUID().toString();
            String stApplyId = "CSJ000000000000001";
    //        String url = json.getString("url");
    //        String fjName =  json.getString("fjName");
            Timestamp  saveTime=new Timestamp(new Date().getTime());
            json.put("stFjId", stFjId);
            json.put("stApplyId", stApplyId);
            json.put("time", saveTime);
            System.out.println("requestData--->"+json);
            threadService.insertData(json);
        }
        
    }

    threadService 类:

    package com.threads.threadPoolInsertData;
    
    import java.io.IOException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import javax.servlet.http.HttpServletRequest;
    import org.springframework.stereotype.Service;
    import com.alibaba.fastjson.JSONObject;
    
    @Service
    public class threadService {
        
        private ExecutorService executorService = Executors.newFixedThreadPool(20);
        
        public void  insertData(JSONObject json) {
            System.out.println("insertData--->"+json);
            executorService.execute(new threadUtil(json) );
        }
        
        
        //接收json参数
             public static String getRequestPostStr(HttpServletRequest request)
                        throws IOException {
                 int contentLength = request.getContentLength();
                    if(contentLength<0){
                        return null;
                    }
                    byte buffer[] = new byte[contentLength];
                    for (int i = 0; i < contentLength;) {
                        int readlen = request.getInputStream().read(buffer, i,
                                contentLength - i);
                        if (readlen == -1) {
                            break;
                        }
                        i += readlen;
                    }
                    String charEncoding = request.getCharacterEncoding();
                    System.out.println(charEncoding);
                    if (charEncoding == null) {
                        charEncoding = "UTF-8";
                    }
                    return new String(buffer, charEncoding);
                }
    }

    threadUtil 类:

    package com.threads.threadPoolInsertData;
    
    import java.sql.Timestamp;
    import com.alibaba.fastjson.JSONObject;
    import...SQL;
    
    public class threadUtil implements Runnable {
    
        private JSONObject json;
        
        public threadUtil(JSONObject json) {
            this.json = json;
        }
    
        @Override
        public void run() {
            System.out.println("threadUtil--->"+json);
            System.out.println("当前线程:"+Thread.currentThread().getName());
            String stFjId = json.getString("stFjId");
            String stApplyId = json.getString("stApplyId");
            String fjName =json.getString("fjName");
            String url = json.getString("url");
            String time = json.getString("time");
            //String 转 Timestamp
            Timestamp saveTime = Timestamp.valueOf(time.toString());
            
            String sql = "insert into DAAN_FJ(ST_ID,APPLY_ID,NAME,URL,TIME) values (?,?,?,?,?)";
            Object[] objects = new Object[] { stFjId, stApplyId, fjName,url,saveTime };
            SQL.execute(sql,objects);
        }
        
        
    }

    自定义线程池:

        //自定义线程池
        private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                                                        2,4,
                                                        60,TimeUnit.SECONDS,
                                                        new ArrayBlockingQueue<>(4),
                                                        Executors.defaultThreadFactory(),
                                                        //自定义拒绝策略
                                                        new MyRejectedExecutionHandler()
                                                        );

    自定义拒绝策略:

    /**
     * 自定义线程池拒绝策略
     */
    public class MyRejectedExecutionHandler implements RejectedExecutionHandler {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
    //拒绝掉的任务 开启新线程去执行
            new Thread(r,"新启线程"+new Random().nextInt(10)).start();
    
    
        }
    }
  • 相关阅读:
    阅读笔记:管理学
    Vs2010中文版MSDN 安装方法
    .NET 产品版权保护方案 (.NET源码加密保护)
    WPF 判断是否为设计(Design)状态
    重写成员时违反了继承安全性规则。重写方法的安全可访问性必须与所重写方法的安全可访问性匹配。
    没有为此解决方案配置选中要生成的项目 .
    何崚谈阿里巴巴前端性能优化最佳实践
    Oracle10GODP连接11G数据库,出现ORA 1017用户名/口令无效; 登录被拒绝 的问题
    HTTP、TCP、UDP、Socket (转)
    编译的时候生成.g.cs还有.g.i.cs,有什么区别?
  • 原文地址:https://www.cnblogs.com/lifan12589/p/13104877.html
Copyright © 2011-2022 走看看