BudWk V7 builds a microservice development framework from scratch - 04 Gateway components

wk-starter-gateway

Secondary path routing and forwarding

The realization of this function is mainly to solve the requirement that the project is divided into multiple microservice modules.

wk-starter-gateway is transformed from nutzcloud-perca , and its NacosServerPrefixSelectorFilter.java is a prefix routing forwarding class, in which

ts.prefix = "/" + ts.name.substring(serviceNamePrefix.length());

This line of code realizes the function of /platform forwarding to xxxx.platform service. It only needs a simple transformation to realize the function of /platform/v1 forwarding to xxxx.platform.v1 service. How to realize it?

.replace(".","/")Just add it, it's easy...

The configuration file is as follows:

jetty:
  contextPath: /platform/v1
nacos:
  discovery:
    server-addr: 192.168.198.19:8848
    namespace: dev
    naming:
      service-name: xxxx.platform.v1 
      meta-data: "{'version':'budwk.platform.v1.7.0.0'}"

IP blacklist

GatewayServletStarter

Before routing and forwarding, you can get the HttpServletRequest clientRequestobject , and if you have a request, it is OK. Get the IP and then judge whether the IP is in the blacklist, and then return proxyResponse.sendError(403);.

log link trace

Same as above, after getting the request, headerappend a string of UUIDs to it, pass it to the microservice module, and then use log4j MDC to print the log.

Websocket support

Because the GatewayServletStarter inherits the AsyncMiddleManServlet class, it is asynchronous, and the Websocket is a long connection and requires a synchronous connection, so the Websocket proxy cannot be directly implemented in the GatewayServletStarter, so please find another way.

Find a class that implements Websocket proxy on GitHub, test OK, and then make a simple transformation to achieve my needs:

WebSocketProxyServlet

Inherit the WebSocketProxyServlet class, and then find the address corresponding to the configured background instance from nacos:

Instance ins = nacosNamingService.selectOneHealthyInstance(serviceName, group);
if (ins != null) {
	redirectUrl = "ws://" + ins.getIp() + ":" + ins.getPort() + url;
}
{{o.name}}
{{m.name}}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324127752&siteId=291194637