The Spring Cloud Gateway integrates Zuul and fuses, so gateways are inherently load-balanced and fused. Therefore, the load balancing algorithm of Spring cloud is the load balancing algorithm of ribbon. In the Ribbon, load balancing defaults to the polling method. What if you want to implement load balancing with a consistent hashing algorithm?
This is where I use guava's consistent hashing algorithm, so I don't write my own consistency hashing algorithm.
First Pom.xml:
<!--Guava cache cache--> <dependency> <groupId>com.google.guava</groupId> < artifactid>guava</artifactid> <version>23.0</version> </dependency>
Then write yourself a class that integrates Abstractloadbalancerrule:
@Component
Public classConsistenthashextendsAbstractloadbalancerrule {PrivateLogger log = Loggerfactory.getlogger (Consistenthash.class); PublicServer Choose (iloadbalancer lb, Object key) {if(LB = =NULL) {Log.warn ("No load Balancer"); return NULL; } Server server=NULL; intCount = 0; while(Server = =NULL&& count++ < 10) {List<Server> reachableservers =lb.getreachableservers (); List<Server> allservers =lb.getallservers (); intUpcount =reachableservers.size (); intServercount =allservers.size (); if((Upcount = = 0) | | (Servercount = = 0) {Log.warn ("No up servers available from load balancer:" +lb); return NULL; } //GET request URIRequestContext CTX =Requestcontext.getcurrentcontext (); HttpServletRequest Request=ctx.getrequest (); String URI= Request.getservletpath () + "?" +request.getquerystring (); intHashcode =Uri.hashcode (); intModel = Hashing.consistenthash (hashcode, Servercount);//a consistent hash that returns the ordinal number directlyServer=Allservers.get (model); if(Server = =NULL) { /*Transient.*/Thread.yield (); Continue; } if(Server.isalive () &&(Server.isreadytoserve ())) { return(server); } //Next.Server =NULL; } if(Count >= 10) {Log.warn ("No available Alive servers after ten tries from load Balancer:" +lb); } returnserver; } @Override PublicServer Choose (Object key) {returnChoose (Getloadbalancer (), key); } @Override Public voidinitwithniwsconfig (Iclientconfig clientconfig) {//TODO auto-generated Method Stub }}
is done.
If you're just trying to achieve consistent hash load balancing for an app, here are a few steps:
1. Remove the annotations above the Consistenthash
2. Create a new class Myribbonconfiguration:
Public class myribbonconfiguration { @Bean public IRule ribbonrule () { return New consistenthash (); // instantiate the policy class corresponding to the configuration file }}
3
= "Hello-service", configuration = myribbonconfiguration. class )publicclass ribbonconfiguration {}
This is just a consistent hash load-balancing algorithm for Hello-service, and the other is polling.
Springcloud load balancing using a consistent hashing algorithm