PHP调用Java类

由于工作需要,需要用PHP调用Java的jar包SDK,不用RPC是因为SDK提供方没有封装这个接口。所以只能用这个方法,亲测可用,不过性能方面则没有测验。废话不说,直接上干货

一、安装Java环境

下载JDK

官网下载地址
http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

解压

cd /usr/local/src
tar zxvf jdk-8u144-linux-i586.tar.gz
mv jdk1.8.044 /usr/local/jdk1.8

配置Java环境

vim /etc/profile
#添加如下配置
#Java Environment
JAVA_HOME=/usr/local/jdk1.8
JRE_HOME=/usr/local/jdk1.8/jre
CLASS_PATH=.:$JRE_HOME/lib/ext:$JAVA_HOME/lib/tools.jar
PATH=$JAVA_HOME/bin:$JRE_HOME/bin:$PATH
export JAVA_HOME JRE_HOME CLASS_PATH PATH

#PHP
PHP_HOME=/usr/local/php
export PATH=$PATH:$PHP_HOME/bin

使配置立即生效

source /etc/profile

检测环境是否正确配置

java -version
#输出以下信息则正确配置
java version "1.8.0_144"
Java(TM) SE Runtime Environment (build 1.8.0_144-b01)
Java HotSpot(TM) Client VM (build 25.144-b01, mixed mode)
php -version
#输出以下信息则正确配置
PHP 5.6.29 (cli) (built: Feb 13 2017 06:17:10) 
Copyright (c) 1997-2016 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies

二、安装php-java-bridge

下载php-java-bridge

官网下载地址
http://php-java-bridge.sourceforge.net/pjb/download.php

解压

cd /usr/local/src
unzip unzip php-java-bridge_7.1.3_documentation.zip #目前版本7.1.3
mkdir /usr/local/php-java-bridge
mv documentation JavaBridge.war /usr/local/php-java-bridge
cd /usr/local/php-java-bridge
mkdir JavaBridge
jar -xvf ./JavaBridge.war ./JavaBridge

测试安装

java -jar JavaBridge.war TestInstallation
#将返回以下信息:
installation okay

如果不能通过安装测试,问题见官网:
http://php-java-bridge.sourceforge.net/pjb/installation.php

启动JavaBridge

cd ./JavaBridge/WEB-INF/lib/
java -jar JavaBridge.jar SERVLET_LOCAL:8080 >/dev/null 2>&1 &
#将会显示以下信息:
Mar 17 01:37:18 JavaBridge INFO : VM                  : 1.8.0_144@http://java.oracle.com/
Mar 17 01:37:18 JavaBridge INFO : JavaBridge version             : 7.1.3    
Mar 17 01:37:18 JavaBridge INFO : logFile             : 
Mar 17 01:37:18 JavaBridge INFO : default logLevel    : 3
Mar 17 01:37:18 JavaBridge INFO : socket              : SERVLET_LOCAL:8080
Mar 17 01:37:18 JavaBridge INFO : java.ext.dirs       : /usr/local/jdk1.8/jre/lib/ext:/usr/java/packages/lib/ext
Mar 17 01:37:18 JavaBridge INFO : php.java.bridge.base: /root
Mar 17 01:37:18 JavaBridge INFO : thread pool size    : 20
Mar 17 01:37:18 JavaBridge INFO : JavaBridgeRunner started on port INET_LOCAL:8080

然后将所需要用到的jar包复制到/usr/local/jdk1.8/jre/lib/ext下

三、php调用Java类

复制Java.inc到你项目中

cp /usr/local/php-java-bridge/JavaBridge/WEB-INF/lib/Java.inc /usr/local/apache/htdocs

编写测试调用Java类的PHP代码

vim /usr/local/apache/htdocs/index.php
<?php 
require_once("./Java.inc");

use java\lang\String as JString;
use java\util\ArrayList as JList;

class String extends JString {
  function toString () {
    return "hello " . parent::toString();
  }
}
$str = new String("Java");

$list = new JList();
$list->add (java_closure($str));
$list->add ("from PHP");
$ar = java_values ($list->toArray());

foreach($ar as $entry) echo "$entry<br>\n"
?>

=>hello Java
from PHP
点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注