In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "the principle and usage of getServiceList in nacos NamingProxy". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn the principle and usage of getServiceList in nacos NamingProxy.
Order
This paper mainly studies the getServiceList of nacos NamingProxy.
NamingProxy.initRefreshSrvIfNeed
Nacos-1.1.3/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java
Public class NamingProxy {private static final int DEFAULT_SERVER_PORT = 8848; private int serverPort = DEFAULT_SERVER_PORT; private String namespaceId; private String endpoint; private String nacosDomain; private List serverList; private List serversFromEndpoint = new ArrayList (); private long lastSrvRefTime = 0L; private long vipSrvRefInterMillis = TimeUnit.SECONDS.toMillis (30); private Properties properties; public NamingProxy (String namespaceId, String endpoint, String serverList) {this.namespaceId = namespaceId; this.endpoint = endpoint If (StringUtils.isNotEmpty (serverList)) {this.serverList = Arrays.asList (serverList.split (",")); if (this.serverList.size () = = 1) {this.nacosDomain = serverList;}} initRefreshSrvIfNeed ();} private void initRefreshSrvIfNeed () {if (StringUtils.isEmpty (endpoint)) {return } ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor (1, new ThreadFactory () {@ Override public Thread newThread (Runnable r) {Thread t = newThread (r); t.setName ("com.alibaba.nacos.client.naming.serverlist.updater"); t.setDaemon (true); return t;}}) ExecutorService.scheduleWithFixedDelay (new Runnable () {@ Override public void run () {refreshSrvIfNeed ();}}, 0, vipSrvRefInterMillis, TimeUnit.MILLISECONDS); refreshSrvIfNeed ();} /. Private void refreshSrvIfNeed () {try {if (! CollectionUtils.isEmpty (serverList)) {NAMING_LOGGER.debug ("server list provided by user:" + serverList); return;} if (System.currentTimeMillis ()-lastSrvRefTime < vipSrvRefInterMillis) {return;} List list = getServerListFromEndpoint () If (CollectionUtils.isEmpty (list)) {throw new Exception ("Can not acquire Nacos list");} if (! CollectionUtils.isEqualCollection (list, serversFromEndpoint)) {NAMING_LOGGER.info ("[SERVER-LIST] server list is updated:" + list);} serversFromEndpoint = list; lastSrvRefTime = System.currentTimeMillis () } catch (Throwable e) {NAMING_LOGGER.warn ("failed to update serverlist", e);}} public List getServerListFromEndpoint () {try {String urlString = "http://" + endpoint +" / nacos/serverlist "; List headers = builderHeaders (); HttpClient.HttpResult result = HttpClient.httpGet (urlString, headers, null, UtilAndComs.ENCODING) If (HttpURLConnection.HTTP_OK! = result.code) {throw new IOException ("Error while requesting:" + urlString + "'. Server returned: "+ result.code);} String content = result.content; List list = new ArrayList (); for (String line: IoUtils.readLines (new StringReader (content) {if (! line.trim (). IsEmpty ()) {list.add (line.trim ()) } return list;} catch (Exception e) {e.printStackTrace ();} return null;} / /.}
The constructor of NamingProxy executes the initRefreshSrvIfNeed method, which registers a scheduled task when the endpoint is not empty, executes the refreshSrvIfNeed method every vipSrvRefInterMillis, and immediately calls the refreshSrvIfNeed method
The refreshSrvIfNeed method will get the serverList update serversFromEndpoint and lastSrvRefTime through the getServerListFromEndpoint () method when serverList is empty and the distance lastSrvRefTime is greater than or equal to vipSrvRefInterMillis.
The getServerListFromEndpoint method requests the / serverlist interface from endpoint to get the serverList returned by the server side
NamingProxy.getServiceList
Nacos-1.1.3/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java
Public class NamingProxy {private static final int DEFAULT_SERVER_PORT = 8848; private int serverPort = DEFAULT_SERVER_PORT; private String namespaceId; private String endpoint; private String nacosDomain; private List serverList; private List serversFromEndpoint = new ArrayList (); private long lastSrvRefTime = 0L; private long vipSrvRefInterMillis = TimeUnit.SECONDS.toMillis (30); private Properties properties; / /. Public ListView getServiceList (int pageNo, int pageSize, String groupName) throws NacosException {return getServiceList (pageNo, pageSize, groupName, null);} public ListView getServiceList (int pageNo, int pageSize, String groupName, AbstractSelector selector) throws NacosException {Map params = new HashMap (4); params.put ("pageNo", String.valueOf (pageNo)); params.put ("pageSize", String.valueOf (pageSize)); params.put (CommonParams.NAMESPACE_ID, namespaceId) Params.put (CommonParams.GROUP_NAME, groupName); if (selector! = null) {switch (SelectorType.valueOf (selector.getType () {case none: break; case label: ExpressionSelector expressionSelector = (ExpressionSelector) selector; params.put ("selector", JSON.toJSONString (expressionSelector)) Break; default: break;}} String result = reqAPI (UtilAndComs.NACOS_URL_BASE + "/ service/list", params); JSONObject json = JSON.parseObject (result); ListView listView = new ListView (); listView.setCount (json.getInteger ("count")) ListView.setData (JSON.parseObject (json.getString ("doms"), new TypeReference () {}); return listView;} public String reqAPI (String api, Map params) throws NacosException {List snapshot = serversFromEndpoint; if (! CollectionUtils.isEmpty (serverList)) {snapshot = serverList;} return reqAPI (api, params, snapshot) } public String reqAPI (String api, Map params, List servers) {return reqAPI (api, params, servers, HttpMethod.GET);} public String reqAPI (String api, Map params, List servers, String method) {params.put (CommonParams.NAMESPACE_ID, getNamespaceId ()); if (CollectionUtils.isEmpty (servers) & & StringUtils.isEmpty (nacosDomain)) {throw new IllegalArgumentException ("no server available") } Exception exception = new Exception (); if (servers! = null & &! servers.isEmpty ()) {Random random = new Random (System.currentTimeMillis ()); int index = random.nextInt (servers.size ()); for (int I = 0; I < servers.size (); iTunes +) {String server = servers.get (index) Try {return callServer (api, params, server, method);} catch (NacosException e) {exception = e; NAMING_LOGGER.error ("request {} failed.", server, e);} catch (Exception e) {exception = e NAMING_LOGGER.error ("request {} failed.", server, e);} index = (index + 1)% servers.size ();} throw new IllegalStateException ("failed to req API:" + api + "after all servers (" + servers + ") tried:" + exception.getMessage ()) } for (int I = 0; I < UtilAndComs.REQUEST_DOMAIN_RETRY_COUNT; iTunes +) {try {return callServer (api, params, nacosDomain);} catch (Exception e) {exception = e; NAMING_LOGGER.error ("[NA] req api:" + api + "failed, server (" + nacosDomain, e)) }} throw new IllegalStateException ("failed to req API:/api/" + api + "after all servers (" + servers + ") tried:" + exception.getMessage ());} /.}
The getServiceList method has an AbstractSelector parameter, which adds the selector parameter to the requested parameter. Currently, ExpressionSelector is added to the label type, and then the reqAPI method is called to request / service/list interface.
The reqAPI method first assigns serversFromEndpoint to snapshot, but if serverList is not empty, it resets snapshot to serverList, and then makes a reqAPI request
The reqAPI method randomizes an index according to servers.size (), and then starts the for loop with servers.size () as the maximum number of loops. In the loop, the server is obtained according to the index and then requests are made through callServer. If the request succeeds, it will jump out of the loop and return. If the request fails, the index will be incremented and the remainder of servers.size () will continue to the next loop. If both requests fail, the IllegalStateException will be thrown at last.
Summary
The constructor of NamingProxy executes the initRefreshSrvIfNeed method, which registers a scheduled task when the endpoint is not empty and executes the refreshSrvIfNeed method every vipSrvRefInterMillis
The refreshSrvIfNeed method will get the serverList update serversFromEndpoint and lastSrvRefTime through the getServerListFromEndpoint () method when serverList is empty and the distance lastSrvRefTime is greater than or equal to vipSrvRefInterMillis.
The getServiceList method takes serverList as the server address list first. If it is empty, then serversFromEndpoint prevails, and then when requesting through the reqAPI method, a server is randomly selected for the request, with a maximum of server.size () requests. If the request succeeds, it will jump out of the loop and return. If the request fails, increment the index and take the remainder of servers.size () to continue the next loop. If both requests fail, IllegalStateException will be thrown at last.
At this point, I believe you have a deeper understanding of "the principle and usage of getServiceList in nacos NamingProxy". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.