py4j

来源:互联网 发布:学页面美工要多少钱 编辑:程序博客网 时间:2024/06/05 10:52

意义:通过python代码去调jvm中的方法和参数,写spark的jobserver中用到
1、pom.xml

        <dependency>            <groupId>org.apache.spark</groupId>            <artifactId>spark-core_2.11</artifactId>            <version>2.2.0</version>        </dependency>

2.python代码

from py4j.java_gateway import JavaGatewaygateway = JavaGateway()                   # connect to the JVMrandom = gateway.jvm.java.util.Random()   # create a java.util.Random instancenumber1 = random.nextInt(10)              # call the Random.nextInt methodnumber2 = random.nextInt(10)print(number1,number2)addition_app = gateway.entry_point        # get the AdditionApplication instanceprint addition_app.addition(number1,number2)

3、java代码

public class Test {        public int addition(int first, int second) {            return first - second;        }        public static void main(String[] args) {            Test app = new Test();            // app is now the gateway.entry_point            GatewayServer server = new GatewayServer(app);            server.start();        }}

注意:python要安装py4j,java代码要先执行

原创粉丝点击