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 principle and function of selectOneHealthyInstance in NacosNamingService

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

Share

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

This article introduces the relevant knowledge of "what is the principle and function of selectOneHealthyInstance in NacosNamingService". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Order

This paper mainly studies the selectOneHealthyInstance of NacosNamingService.

NacosNamingService

Nacos-1.1.3/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java

Public class NacosNamingService implements NamingService {private static final String DEFAULT_PORT = "8080"; private static final long DEFAULT_HEART_BEAT_INTERVAL = TimeUnit.SECONDS.toMillis (5); / * * Each Naming instance should have different namespace. * / private String namespace; private String endpoint; private String serverList; private String cacheDir; private String logName; private HostReactor hostReactor; private BeatReactor beatReactor; private EventDispatcher eventDispatcher; private NamingProxy serverProxy; / /. Override public Instance selectOneHealthyInstance (String serviceName) throws NacosException {return selectOneHealthyInstance (serviceName, new ArrayList ());} @ Override public Instance selectOneHealthyInstance (String serviceName, String groupName) throws NacosException {return selectOneHealthyInstance (serviceName, groupName, true);} @ Override public Instance selectOneHealthyInstance (String serviceName, boolean subscribe) throws NacosException {return selectOneHealthyInstance (serviceName, new ArrayList (), subscribe) @ Override public Instance selectOneHealthyInstance (String serviceName, String groupName, boolean subscribe) throws NacosException {return selectOneHealthyInstance (serviceName, groupName, new ArrayList (), subscribe);} @ Override public Instance selectOneHealthyInstance (String serviceName, List clusters) throws NacosException {return selectOneHealthyInstance (serviceName, clusters, true);} @ Override public Instance selectOneHealthyInstance (String serviceName, String groupName, List clusters) throws NacosException {return selectOneHealthyInstance (serviceName, groupName, clusters, true) } @ Override public Instance selectOneHealthyInstance (String serviceName, List clusters, boolean subscribe) throws NacosException {return selectOneHealthyInstance (serviceName, Constants.DEFAULT_GROUP, clusters, subscribe) } @ Override public Instance selectOneHealthyInstance (String serviceName, String groupName, List clusters, boolean subscribe) throws NacosException {if (subscribe) {return Balancer.RandomByWeight.selectHost (NamingUtils.getGroupedName (serviceName, groupName), StringUtils.join (clusters, ",") } else {return Balancer.RandomByWeight.selectHost (hostReactor.getServiceInfoDirectlyFromServer (NamingUtils.getGroupedName (serviceName, groupName), StringUtils.join (clusters, ","));}} /.}

SelectOneHealthyInstance is similar to selectInstances, except that it returns a single instance;selectOneHealthyInstance and gets the serviceInfo from hostReactor first.

If subscribe is true, execute hostReactor.getServiceInfo to get serviceInfo, otherwise execute hostReactor.getServiceInfoDirectlyFromServer to get serviceInfo

After obtaining the serviceInfo, selectOneHealthyInstance uses the Balancer.RandomByWeight.selectHost method to select the instance of a single healthy

Balancer

Nacos-1.1.3/client/src/main/java/com/alibaba/nacos/client/naming/core/Balancer.java

Public class Balancer {/ * report status to server * / public final static List UNCONSISTENT_SERVICE_WITH_ADDRESS_SERVER = new CopyOnWriteArrayList (); public static class RandomByWeight {public static List selectAll (ServiceInfo serviceInfo) {List hosts = serviceInfo.getHosts (); if (CollectionUtils.isEmpty (hosts)) {throw new IllegalStateException ("no host to srv for serviceInfo:" + serviceInfo.getName ()) } return hosts;} public static Instance selectHost (ServiceInfo dom) {List hosts = selectAll (dom); if (CollectionUtils.isEmpty (hosts)) {throw new IllegalStateException ("no host to srv for service:" + dom.getName ());} return getHostByRandomWeight (hosts) }} / * Return one host from the host list by random-weight. * * @ param hosts The list of the host. * @ return The random-weight result of the host * / protected static Instance getHostByRandomWeight (List hosts) {NAMING_LOGGER.debug ("entry randomWithWeight"); if (hosts = = null | | hosts.size () = = 0) {NAMING_LOGGER.debug ("hosts = = null | | hosts.size () = = 0"); return null;} Chooser vipChooser = new Chooser ("www.taobao.com") NAMING_LOGGER.debug ("new Chooser"); List hostsWithWeight = new ArrayList (); for (Instance host: hosts) {if (host.isHealthy ()) {hostsWithWeight.add (new Pair (host, host.getWeight ();} NAMING_LOGGER.debug ("for (Host host: hosts)"); vipChooser.refresh (hostsWithWeight) NAMING_LOGGER.debug ("vipChooser.refresh"); return vipChooser.randomWithWeight ();}}

Balancer's RandomByWeight provides selectAll and selectHost methods; selectAll makes a null judgment for serviceInfo.getHosts (), and throws an IllegalStateException if empty

The selectAll method is called inside the selectHost method, which finally selects the instance of a single healthy through getHostByRandomWeight.

The getHostByRandomWeight method first creates a Chooser, then selects the instance of healthy to construct hostsWithWeight, then uses vipChooser.refresh (hostsWithWeight) to refresh, and finally selects the instance of a single healthy through vipChooser.randomWithWeight ().

Chooser

Nacos-1.1.3/client/src/main/java/com/alibaba/nacos/client/naming/utils/Chooser.java

Public class Chooser {private K uniqueKey; private volatile Ref ref; public T random () {List items = ref.items; if (items.size () = = 0) {return null;} if (items.size () = = 1) {return items.get (0);} return items.get (ThreadLocalRandom.current (). NextInt (items.size () } public T randomWithWeight () {Ref ref = this.ref; double random = ThreadLocalRandom.current (). NextDouble (0,1); int index = Arrays.binarySearch (ref.weights, random); if (index)

< 0) { index = -index - 1; } else { return ref.items.get(index); } if (index >

= 0 & & index < ref.weights.length) {if (random < ref.weights [index]) {return ref.items.get (index);}} / * This should never happen, but it ensures we will return a correct * object in case there is some floating point inequality problem * wrt the cumulative probabilities. * / return ref.items.get (ref.items.size ()-1);} public Chooser (K uniqueKey) {this (uniqueKey, new ArrayList ());} public Chooser (K uniqueKey, List pairs) {Ref ref = new Ref (pairs); ref.refresh (); this.uniqueKey = uniqueKey; this.ref = ref;} public K getUniqueKey () {return uniqueKey } public Ref getRef () {return ref;} public void refresh (List itemsWithWeight) {Ref newRef = newRef (itemsWithWeight); newRef.refresh (); newRef.poller = this.ref.poller.refresh (newRef.items); this.ref = newRef;} / /.}

The refresh method of Chooser creates the Ref based on itemsWithWeight, and then executes the refresh method of Ref; the randomWithWeight method creates the initial index through Arrays.binarySearch (ref.weights, random), and then fetches the element from ref.items according to index

Ref

Nacos-1.1.3/client/src/main/java/com/alibaba/nacos/client/naming/utils/Chooser.java

Public class Ref {private List itemsWithWeight = new ArrayList (); private List items = new ArrayList (); private Poller poller = new GenericPoller (items); private double [] weights; @ SuppressWarnings ("unchecked") public Ref (List itemsWithWeight) {this.itemsWithWeight = itemsWithWeight;} public void refresh () {Double originWeightSum = (double) 0 For (Pair item: itemsWithWeight) {double weight = item.weight (); / / ignore item which weight is zero.see test_randomWithWeight_weight0 in ChooserTest if (weight

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