java有非常好的执行性能,而php有高效、低成本的开发和部署能力,所以已经有很多前辈做了大量的集成java和php的尝试,其中的佼佼者要数resin的quercus,还有和php-fpm通讯的框架jfastcgi,然而两者都是运行在http server上的(其中quercus运行php想得到很高的性能,还要掏银子),如果我们需要一个直接和php-fpm通讯,又不想和http server扯上关系,比如做一个基于socket长连的web game,用php来实现游戏逻辑,用java来开发一个接受socket client请求并且转发请求给php的中间层,那用jfastcgi或者quercus就有些无能为力了。
这段时间工作比较闲,所以就花了些时间研究了一下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();