多线程批量静态化 java与php【原创】

需求描述:现在网站的数量达到了3万多篇,全站都是静态化的,然而有时候改了网站的导航,问题大了。怎么办?跑php?单线程造成了我不得不停下其他工作,只为了跑脚本。而且中间可能会遇到错误,我又得重新开始跑。

其次,进度条的问题?php在跑脚本的时候 除非在cli下,不然cgi下根本不知道后台执行的进度。这个问题相到的大。

解决方案1:参考张宴的文章, 他采用了php扩展机制,支持多线程。

解决方案2:用java来写,java原生就支持多线程的。而且IO性能好。(不用修改原来的代码) 支持进度条反馈。

思路:多线程采集新闻的方式。

接下来是代码实现,我稍候发布出来。

参考资料:http://blog.s135.com/pthreads/

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class WebContent {
 private static int kernel = 4;// 针对服务器内核数
 public static void main(String args[]) {
  MyThread t = new MyThread();
  for (int i = 0; i < kernel; i++) {
   new Thread(t).start();
  }
 }
}
class MyThread implements Runnable {
 private int tickets = 34000;
 @Override
 public void run() {
  String url = "http://www.d-shang.com/news/v/?id=";
  // 获取id
  while (tickets > 0) {
   String filename = tickets + "";
   // 创建文件
   try {
    String content = getOneHtml(url, filename);
    if (content == null || content.length() < 200) {
     System.out.print(filename + " 线程"
       + Thread.currentThread().getId() + "不存在 跳过\r\n");
     tickets--;
     continue;
    }
    File file = new File("c:\\a/" + filename + ".html");
    Writer out = null;
    out = new FileWriter(file);
    out.write(content);
    out.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   System.out.print(filename + " 线程" + Thread.currentThread().getId()
     + "已生成 \r\n");
   tickets--;
  }
 }
 /**
  * 读取一个网页全部内容
  */
 public String getOneHtml(String htmlurl, String filename)
   throws IOException {
  URL url;
  String temp;
  final StringBuffer sb = new StringBuffer();
  try {
   url = new URL(htmlurl + filename);
   HttpURLConnection httpCon = (HttpURLConnection) url
     .openConnection();
   httpCon.setConnectTimeout(2000);
   httpCon.setReadTimeout(2000);
   httpCon.connect();// 建立连接
   final BufferedReader in = new BufferedReader(new InputStreamReader(
     url.openStream(), "utf-8"));// 读取网页全部内容
   while ((temp = in.readLine()) != null) {
    sb.append(temp);
   }
   in.close();
  } catch (final MalformedURLException me) {
   System.out.println("你输入的URL格式有问题!请仔细输入");
   me.getMessage();
   throw me;
  } catch (final IOException e) {
   return null;
  }
  return sb.toString();
 }
}

转载于:https://my.oschina.net/u/554046/blog/220184

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值