首页  >  文章  >  后端开发  >  用Java连接php-fpm

用Java连接php-fpm

WBOY
WBOY原创
2016-06-23 14:31:331086浏览

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完整请求的代码:

              <p class="sycode">              //    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    <    String, String    >     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();              </p>

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn