用Java连接php-fpm
这段时间工作比较闲,所以就花了些时间研究了一下FastCGI协议,读了一遍jfastcgi的源代码,写了fcgi4j这个小工具库。
该工具库的jar包和源代码可以从http://code.google.com/p/fcgi4j/上下载,欢迎拍砖或者修改再利用。
下面是用fcgi4j来实现一个php-fpm完整请求的代码:
// create FastCGI connection FCGIConnection connection = FCGIConnection.open();connection.connect( new InetSocketAddress( " 127.0.0.1 " , 9000 ));connection.beginRequest( " fcgi.php " ); // set the HTTP METHOD,GET for default connection.setRequestMethod( " post " ); // set the queryString, not required when no queryString connection.setQueryString( " text=hello " ); // add FCGIParams connection.addParams( " DOCUMENT_ROOT " , " /var/www " ); byte [] postData = " hello=world " .getBytes(); // set contentLength, it's importent connection.setContentLength(postData.length);connection.write(ByteBuffer.wrap(postData)); // print response headers Map responseHeaders = connection.getResponseHeaders(); for (String key : responseHeaders.keySet()){ System.out.println( " HTTP HEADER: " + key + " -> " + responseHeaders.get(key));} // read response data ByteBuffer buffer = ByteBuffer.allocate( 10240 );connection.read(buffer);buffer.flip(); byte [] data = new byte [buffer.remaining()];buffer.get(data);System.out.println( new String(data)); // close the connection connection.close();