在CentOS系统上,Python和Java可以通过多种方式实现交互。以下是一些常见的方法:
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/api/data', methods=['GET'])
def get_data():
return jsonify({"message": "Hello from Python!"})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientExample {
public static void main(String[] args) {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet request = new HttpGet("http://localhost:5000/api/data");
try (CloseableHttpResponse response = httpClient.execute(request)) {
System.out.println(EntityUtils.toString(response.getEntity()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='', routing_key='hello', body='Hello from Python!')
print(" [x] Sent 'Hello from Python!'")
connection.close()
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class RabbitMQExample {
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello from Java!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
}
}
}
这种方法较为复杂,通常用于性能敏感的场景。
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 12345))
server_socket.listen(5)
while True:
client_socket, addr = server_socket.accept()
print(f"Connection from {addr}")
client_socket.sendall(b"Hello from Python!")
client_socket.close()
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
public class TCPClientExample {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 12345);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
String response = in.readLine();
System.out.println(response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
选择哪种方法取决于具体的需求和场景。HTTP REST API是最简单和最常用的方法,适用于大多数情况。消息队列适用于需要异步处理和解耦的场景。JNI适用于性能敏感的场景,但实现复杂。Socket通信适用于需要实时双向通信的场景。