|
8 | 8 |
|
9 | 9 | import java.io.*; |
10 | 10 | import java.util.HashMap; |
| 11 | +import java.util.Properties; |
| 12 | +import java.util.Set; |
11 | 13 |
|
12 | 14 | /** |
13 | 15 | * 操作nginx的服务 |
@@ -49,6 +51,51 @@ public class NginxService { |
49 | 51 | } |
50 | 52 | } |
51 | 53 |
|
| 54 | + } |
| 55 | + |
| 56 | + /** |
| 57 | + * 负载均衡策略 |
| 58 | + */ |
| 59 | + private final HashMap<String, String> loadBalancingStrategys; |
| 60 | + |
| 61 | + { |
| 62 | + String path = Constant.rootPath + "loadBalancingStrategy.properties"; |
| 63 | + if (new File(path).exists()) { |
| 64 | + Properties p = new Properties(); |
| 65 | + try { |
| 66 | + p.load(ResourcesReader.readStream(path)); |
| 67 | + } catch (IOException e) { |
| 68 | + throw new RuntimeException("loadBalancingStrategy.properties config err", e); |
| 69 | + } |
| 70 | + Set<String> appNames = p.stringPropertyNames(); |
| 71 | + loadBalancingStrategys = new HashMap<>(appNames.size()); |
| 72 | + for (String appName : appNames) { |
| 73 | + String value = p.getProperty(appName); |
| 74 | + String strategy; |
| 75 | + switch (value) { |
| 76 | + case "least_conn": |
| 77 | + strategy = "\tleast_conn;\n"; |
| 78 | + break; |
| 79 | + case "ip_hash": |
| 80 | + strategy = "\tip_hash;\n"; |
| 81 | + break; |
| 82 | + case "polling": |
| 83 | + strategy = ""; |
| 84 | + break; |
| 85 | + case "url_hash": |
| 86 | + strategy = "\thash $request_uri;\n"; |
| 87 | + break; |
| 88 | + case "fair": |
| 89 | + strategy = "\tfair;\n"; |
| 90 | + break; |
| 91 | + default: |
| 92 | + strategy = "\tleast_conn;\n"; |
| 93 | + } |
| 94 | + loadBalancingStrategys.put(appName, strategy); |
| 95 | + } |
| 96 | + } else { |
| 97 | + loadBalancingStrategys = new HashMap<>(0); |
| 98 | + } |
52 | 99 |
|
53 | 100 | } |
54 | 101 |
|
@@ -77,9 +124,14 @@ private void writeCfg(Record record) { |
77 | 124 | for (ServiceRecord service : services) { |
78 | 125 | String[] urls = service.getServiceUrls(); |
79 | 126 | String appName = service.getName(); |
| 127 | + //upstream |
80 | 128 | sbUpstream.append("upstream upstream-").append(appName).append("{\n"); |
81 | | - sbUpstream.append("\tleast_conn;\n"); |
82 | | - |
| 129 | + String loadBalancingStrategy = loadBalancingStrategys.get(appName); |
| 130 | + if (null == loadBalancingStrategy) { |
| 131 | + loadBalancingStrategy = "\tleast_conn;\n"; |
| 132 | + } |
| 133 | + sbUpstream.append(loadBalancingStrategy); |
| 134 | + //location |
83 | 135 | sbServer.append("location ^~ /").append(appName).append("/ {\n"); |
84 | 136 | sbServer.append("\tproxy_pass http://upstream-").append(appName).append(";\n"); |
85 | 137 | String param = locationParams.get(appName); |
|
0 commit comments