1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| @Service public class NginxConfigManager { @Value("${nginx.config.path}") private String nginxConfigPath; @Value("${nginx.reload.command}") private String nginxReloadCommand;
public void addBackendServer(String upstream, String server) { String config = readNginxConfig(); config = addServerToUpstream(config, upstream, server); writeNginxConfig(config); reloadNginx(); }
public void removeBackendServer(String upstream, String server) { String config = readNginxConfig(); config = removeServerFromUpstream(config, upstream, server); writeNginxConfig(config); reloadNginx(); }
public void updateServerWeight(String upstream, String server, int weight) { String config = readNginxConfig(); config = updateServerWeightInUpstream(config, upstream, server, weight); writeNginxConfig(config); reloadNginx(); } private String readNginxConfig() { try { return Files.readString(Path.of(nginxConfigPath)); } catch (IOException e) { throw new RuntimeException("Failed to read nginx config", e); } } private void writeNginxConfig(String config) { try { Files.writeString(Path.of(nginxConfigPath), config); } catch (IOException e) { throw new RuntimeException("Failed to write nginx config", e); } } private void reloadNginx() { try { Process process = Runtime.getRuntime().exec(nginxReloadCommand); int exitCode = process.waitFor(); if (exitCode != 0) { throw new RuntimeException("Failed to reload nginx, exit code: " + exitCode); } } catch (Exception e) { throw new RuntimeException("Failed to reload nginx", e); } } private String addServerToUpstream(String config, String upstream, String server) { String pattern = String.format("upstream\\s+%s\\s*\\{", upstream); String replacement = String.format("upstream %s {\n server %s;", upstream, server); return config.replaceAll(pattern, replacement); } private String removeServerFromUpstream(String config, String upstream, String server) { String pattern = String.format("server\\s+%s[^;]*;", server); return config.replaceAll(pattern, ""); } private String updateServerWeightInUpstream(String config, String upstream, String server, int weight) { String pattern = String.format("server\\s+%s[^;]*;", server); String replacement = String.format("server %s weight=%d;", server, weight); return config.replaceAll(pattern, replacement); } }
|