Java:使用 psql 命令的 ProcessBuilder、使用 kubectl 端口转发的 ProcessBuilder 不会连接到数据库。相同的命令适用于 cmdline

问题描述 投票:0回答:1

操作系统:DISTRIB_ID=Ubuntu DISTRIB_RELEASE=20.04

DISTRIB_DESCRIPTION =“Ubuntu 20.04.6 LTS”psql:psql(PostgreSQL)12.20

(Ubuntu 12.20-0ubuntu0.20.04.1) Java: openjdk 版本“11.0.24”

2024-07-16 OpenJDK 运行时环境(build 11.0.24+8-post-Ubuntu-1ubuntu320.04) OpenJDK 64 位服务器虚拟机(build 11.0.24+8-post-Ubuntu-1ubuntu320.04,混合模式,分享)

如果我在命令行上运行以下两个命令,它工作正常并且我可以检索数据(在这种情况下,用户没有密码):

kubectl port-forward service/service-name 7432:5432
psql -h localhost -p 7432 -U username -d database -w -t -c "select id from foo.bar where id='1'"

我有端口转发的方法:

public static Process portForward(String type, String deploymentName, String containerPort, String localPort) {

    Predicate<Process> readyPredicate = Objects::nonNull;
    String command = "kubectl port-forward " + type + "/" + deploymentName + " " + containerPort + ":" + localPort;
    ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash", "-c", command);
    Process process;

    try {
        process = processBuilder.start();
        final Thread thread = new Thread(process::destroyForcibly);
        Runtime.getRuntime().addShutdownHook(thread);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    if (!readyPredicate.test(process)) {
        final String errorMsg = String.format("Deployment '" + deploymentName + "' was not ready");
        throw new IllegalStateException(errorMsg);
    }

    return process;
}

如果我在命令行上运行端口转发,该过程如下所示: kubectl port-forward cmd line

如果我通过 Java ProcessBuilder 运行端口转发,该过程如下所示: kubectl port-forward Java code

两者没有区别。 psql命令的方法:

public static boolean psqlQuery() {
    final ProcessBuilder processBuilder = new ProcessBuilder("sh", "-c", "psql -h localhost -p 7432 -U username -d database -w -t -c \"select id from foo.bar where id='1'\"");

    try {
        Process process = processBuilder.start();
        process.waitFor();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        List<String> output = reader.lines().collect(Collectors.toList());
        output.forEach(LOGGER::info);

        BufferedReader errorreader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        List<String> erroroutput = errorreader.lines().collect(Collectors.toList());
        erroroutput.forEach(LOGGER::error);

        return output.stream().anyMatch(c -> c.contains("1"));
    } catch (IOException | InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new RuntimeException(e);
    }
}

我正在运行 portForward 方法,然后运行 psqlQuery 方法。 这不起作用,并给出一条错误消息,指出它无法连接,但如果当我从 cmd 行运行 portForward 时运行 psqlQuery,它就可以正常工作。

任何帮助将不胜感激。

java psql kubectl processbuilder portforwarding
1个回答
0
投票

所以我实际上在写完这篇文章后立即开始工作,但我将其放在这里以防万一它对某人有帮助。 代码执行得太快并且端口转发尚未准备好,因此只需添加

Thread.sleep(2000)
就足以修复它。

© www.soinside.com 2019 - 2024. All rights reserved.