62b82b12862942fb609075db4f96f72dfd28a358
\345\210\206\345\270\203\345\274\217\347\263\273\347\273\237\346\236\266\346\236\204\346\226\271\346\241\210\350\256\276\350\256\241\345\210\235\347\250\277.md
... | ... | @@ -201,6 +201,56 @@ sidecar 回调,如果不成功会一直尝试: |
201 | 201 | |
202 | 202 | [[http://iidp.chinasie.com:9999/iidpminio/design/gateway.png]] |
203 | 203 | |
204 | +基于okHttp进行转发 |
|
205 | + |
|
206 | +```java |
|
207 | + |
|
208 | + |
|
209 | +public class ReverseProxyServlet extends HttpServlet { |
|
210 | + |
|
211 | + private final List<String> targets; |
|
212 | + private final Random random = new Random(); |
|
213 | + private final OkHttpClient client = new OkHttpClient(); |
|
214 | + |
|
215 | + public ReverseProxyServlet(List<String> targets) { |
|
216 | + this.targets = targets; |
|
217 | + } |
|
218 | + |
|
219 | + @Override |
|
220 | + protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { |
|
221 | + String target = targets.get(random.nextInt(targets.size())); |
|
222 | + String targetUrl = target + req.getRequestURI(); |
|
223 | + |
|
224 | + Request proxyRequest = new Request.Builder() |
|
225 | + .url(targetUrl) |
|
226 | + .build(); |
|
227 | + |
|
228 | + try (Response proxyResponse = client.newCall(proxyRequest).execute()) { |
|
229 | + resp.setStatus(proxyResponse.code()); |
|
230 | + if (proxyResponse.body() != null) { |
|
231 | + resp.getOutputStream().write(proxyResponse.body().bytes()); |
|
232 | + } |
|
233 | + } |
|
234 | + } |
|
235 | + |
|
236 | + public static void main(String[] args) throws Exception { |
|
237 | + List<String> targets = new ArrayList<>(); |
|
238 | + targets.add("http://localhost:9091"); |
|
239 | + targets.add("http://localhost:9092"); |
|
240 | + |
|
241 | + Server server = new Server(9090); |
|
242 | + ServletContextHandler context = new ServletContextHandler(); |
|
243 | + context.setContextPath("/"); |
|
244 | + server.setHandler(context); |
|
245 | + |
|
246 | + context.addServlet(new ServletHolder(new ReverseProxyServlet(targets)), "/*"); |
|
247 | + server.start(); |
|
248 | + server.join(); |
|
249 | + } |
|
250 | +} |
|
251 | + |
|
252 | +``` |
|
253 | + |
|
204 | 254 | #### 2.2 MySQL 维护app和容器服务的关系 |
205 | 255 | |
206 | 256 | 在 MySQL 中维护app和其所在容器服务的关系。每个 Pod 中可在进程内缓存这些关系,并设置有效期(如 5 分钟)。如果缓存未过期但访问失败,则强制从 MySQL 读取,以确保数据的正确性。 |