Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the function of DistroFilter in nacos

2025-01-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article shows you what the role of DistroFilter in nacos is, the content is concise and easy to understand, it can definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

CanDistro

Nacos-1.1.3/naming/src/main/java/com/alibaba/nacos/naming/web/CanDistro.java

@ Retention (RetentionPolicy.RUNTIME) public @ interface CanDistro {}

CanDistro is used to identify a method that needs to determine whether it should be redirected according to distro.

DistroFilter

Nacos-1.1.3/naming/src/main/java/com/alibaba/nacos/naming/web/DistroFilter.java

Public class DistroFilter implements Filter {private static final int PROXY_CONNECT_TIMEOUT = 2000; private static final int PROXY_READ_TIMEOUT = 2000; @ Autowired private DistroMapper distroMapper; @ Autowired private SwitchDomain switchDomain; @ Autowired private FilterBase filterBase; @ Override public void init (FilterConfig filterConfig) throws ServletException {} @ Override public void doFilter (ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {HttpServletRequest req = (HttpServletRequest) servletRequest; HttpServletResponse resp = (HttpServletResponse) servletResponse String urlString = req.getRequestURI (); if (StringUtils.isNotBlank (req.getQueryString () {urlString + = "?" + req.getQueryString ();} try {String path = new URI (req.getRequestURI ()). GetPath (); String serviceName = req.getParameter (CommonParams.SERVICE_NAME) / / For client under 0.8.0: if (StringUtils.isBlank (serviceName)) {serviceName = req.getParameter ("dom");} Method method = filterBase.getMethod (req.getMethod (), path); if (method = = null) {throw new NoSuchMethodException (req.getMethod () + "+ path) } String groupName = req.getParameter (CommonParams.GROUP_NAME); if (StringUtils.isBlank (groupName)) {groupName = Constants.DEFAULT_GROUP;} / / use groupName@@serviceName as new service name: String groupedServiceName = serviceName If (StringUtils.isNotBlank (serviceName) & &! serviceName.contains (Constants.SERVICE_INFO_SPLITER)) {groupedServiceName = groupName + Constants.SERVICE_INFO_SPLITER + serviceName;} / / proxy request to other server if necessary: if (method.isAnnotationPresent (CanDistro.class) & &! distroMapper.responsible (groupedServiceName)) {String userAgent = req.getHeader ("User-Agent") If (StringUtils.isNotBlank (userAgent) & & userAgent.contains (UtilsAndCommons.NACOS_SERVER_HEADER)) {/ / This request is sent from peer server, should not be redirected again: Loggers.SRV_LOG.error ("receive invalid redirect request from peer {}" req.getRemoteAddr ()) Resp.sendError (HttpServletResponse.SC_BAD_REQUEST, "receive invalid redirect request from peer" + req.getRemoteAddr ()); return;} List headerList = new ArrayList (16); Enumeration headers = req.getHeaderNames () While (headers.hasMoreElements ()) {String headerName = headers.nextElement (); headerList.add (headerName); headerList.add (req.getHeader (headerName)) } HttpClient.HttpResult result = HttpClient.request ("http://" + distroMapper.mapSrv (groupedServiceName) + urlString, headerList, StringUtils.isBlank (req.getQueryString ())? HttpClient.translateParameterMap (req.getParameterMap ()): new HashMap (2), PROXY_CONNECT_TIMEOUT, PROXY_READ_TIMEOUT, "UTF-8", req.getMethod (); try {resp.setCharacterEncoding ("UTF-8"); resp.getWriter () .write (result.content); resp.setStatus (result.code) } catch (Exception ignore) {Loggers.SRV_LOG.warn ("[DISTRO-FILTER] request failed:" + distroMapper.mapSrv (groupedServiceName) + urlString);} return;} OverrideParameterRequestWrapper requestWrapper = OverrideParameterRequestWrapper.buildRequest (req); requestWrapper.addParameter (CommonParams.SERVICE_NAME, groupedServiceName); filterChain.doFilter (requestWrapper, resp) } catch (AccessControlException e) {resp.sendError (HttpServletResponse.SC_FORBIDDEN, "access denied:" + UtilsAndCommons.getAllExceptionMsg (e)); return;} catch (NoSuchMethodException e) {resp.sendError (HttpServletResponse.SC_NOT_IMPLEMENTED, "no such api:" + e.getMessage ()); return } catch (Exception e) {resp.sendError (HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Server failed," + UtilsAndCommons.getAllExceptionMsg (e)); return;}} @ Override public void destroy () {}}

DistroFilter implements the Filter interface of servlet; its doFilter method reads serviceName, method, groupName, etc., from servletRequest, and then determines whether the method is marked with CanDistro. If so and distroMapper is not responsible for the service, it builds a http request and writes the result back to Filter;. If redirection is not needed, continue filterChain.doFilter.

HttpClient.request

Nacos-1.1.3/naming/src/main/java/com/alibaba/nacos/naming/misc/HttpClient.java

Public class HttpClient {private static final int TIME_OUT_MILLIS = 10000; private static final int CON_TIME_OUT_MILLIS = 5000; private static AsyncHttpClient asyncHttpClient; private static CloseableHttpClient postClient; / /. Public static HttpResult request (String url, List headers, Map paramValues, int connectTimeout, int readTimeout, String encoding, String method) {HttpURLConnection conn = null; try {String encodedContent = encodingParams (paramValues, encoding); url + = (null = = encodedContent)? ": ("? "+ encodedContent); conn = (HttpURLConnection) new URL (url). OpenConnection (); conn.setConnectTimeout (connectTimeout) Conn.setReadTimeout (readTimeout); conn.setRequestMethod (method); conn.addRequestProperty ("Client-Version", UtilsAndCommons.SERVER_VERSION); conn.addRequestProperty ("User-Agent", UtilsAndCommons.SERVER_VERSION); setHeaders (conn, headers, encoding); conn.connect (); return getResult (conn) } catch (Exception e) {Loggers.SRV_LOG.warn ("Exception while request: {}, caused: {}", url, e); return new HttpResult (500, e.toString (), Collections.emptyMap ());} finally {if (conn! = null) {conn.disconnect () }} private static HttpResult getResult (HttpURLConnection conn) throws IOException {int respCode = conn.getResponseCode (); InputStream inputStream; if (HttpURLConnection.HTTP_OK = = respCode) {inputStream = conn.getInputStream ();} else {inputStream = conn.getErrorStream ();} Map respHeaders = new HashMap (conn.getHeaderFields (). Size ()) For (Map.Entry entry: conn.getHeaderFields (). EntrySet ()) {respHeaders.put (entry.getKey (), entry.getValue (). Get (0));} String gzipEncoding = "gzip"; if (gzipEncoding.equals (respHeaders.get (HttpHeaders.CONTENT_ENCODING) {inputStream = new GZIPInputStream (inputStream) } HttpResult result = new HttpResult (respCode, IOUtils.toString (inputStream, getCharset (conn)), respHeaders); inputStream.close (); return result;} public static class HttpResult {final public int code; final public String content; final private Map respHeaders; public HttpResult (int code, String content, Map respHeaders) {this.code = code; this.content = content This.respHeaders = respHeaders;} public String getHeader (String name) {return respHeaders.get (name);} /.}

The request method of HttpClient directly uses the HttpURLConnection of jdk to make the request. The returned result is encapsulated as HttpResult, and its content is the body of the response.

Summary

DistroFilter implements the Filter interface of servlet; its doFilter method reads serviceName, method, groupName, etc., from servletRequest, and then determines whether the method is marked with CanDistro. If so and distroMapper is not responsible for the service, it builds a http request and writes the result back to Filter;. If redirection is not needed, continue filterChain.doFilter.

The above content is what is the role of DistroFilter in nacos. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report