In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
In this issue, the editor will bring you about the meaning of load balancing in Java Spring Cloud. The article is rich in content and analyzes and describes it from a professional point of view. I hope you can get something after reading this article.
1. Overview of Ribbon client load balancer 1.1 Ribbon
Ribbon is a client-side load balancing tool based on HTTP and TCP provided by Netflix.
Ribbon has two main functions:
Simplify remote invocation
Load balancing
The difference between client load balancing and server load balancing
Server load balancing
Load balancing algorithm is on the server side
Service address list maintained by load balancer
Client load balancing
Load balancing algorithm on the client side
Client maintenance service address list
1.2 Ribbon remote invocation
Ribbon simplifies remote calls to RestTemplate.
The remote calls in the original Provider are as follows:
@ GetMapping ("/ goods/ {id}") public Goods findGoodsById (@ PathVariable ("id") int id) {/ / demonstrate that discoveryClient uses List instances = discoveryClient.getInstances ("eureka-provider"); / / determine whether the collection has data if (instances = = null | | instances.size () = 0) {/ / the collection has no data return null;} ServiceInstance instance = instances.get (0); String host = instance.getHost () / / get ip int port = instance.getPort (); / / get port System.out.println (host); System.out.println (port); String url = "http://"+host+":"+port+"/goods/findOne/"+id; / / 3. Call method Goods goods = restTemplate.getForObject (url, Goods.class); return goods;}
Use Ribbon to simplify restTemplate calls:
1. When declaring the Bean of restTemplate, add an annotation: @ LoadBalanced
Configurationpublic class RestTemplateConfig {@ LoadBalanced @ Bean public RestTemplate restTemplate () {return new RestTemplate ();}}
two。 When you need to define a url when initiating a request using restTemplate, host:port can be replaced with the application name of the service provider
@ GetMapping ("/ goods2/ {id}") public Goods findGoodsById2 (@ PathVariable ("id") int id) {String url = "http://EUREKA-PROVIDER/goods/findOne/"+id; / / 3. Call method Goods goods = restTemplate.getForObject (url, Goods.class); return goods;} 1.3 Ribbon load balancer
1. Since we want to load balance, we need to start multiple Provider services to form a cluster. Before starting, we need to modify Provider to set the port number to the product title.
Package com.zt.provider.controller;/** * GoodsController provider * / @ RestController@RequestMapping ("/ goods") public class GoodsController {@ Value ("${server.port}") private int port; @ Autowired private GoodsService goodsService; @ GetMapping ("/ findOne/ {id}") public Goods findOne (@ PathVariable ("id") int id) {Goods goods = goodsService.findOne (id) Goods.setTitle (goods.getTitle () + ":" + port); / / set the port number to the product title return goods;}}
two。 Next, start Provider with multiple examples, select edit configurations-- > check allow parallel run
3. Then start Provider with port numbers of 8001 and 8002, respectively
4. Start Consumer for testing
Http://localhost:9000/order/goods2/1
Use polling to call two 8001 and 8002 Provider
{"id": 1, "title": "Huawei Mobile: 8001", "price": 3999.0, "count": 10000} {"id": 1, "title": "Huawei Mobile: 8002", "price": 3999.0, "count": 10000} Ribbon load balancing policy class name description RandomRule random policy random selection serverRoundRobinRule polling policy polling selection, polling index, select Server corresponding to index location RetryRule retry policy for the selected load balancing policy machine retry mechanism, if the selection of Server is not successful within a configuration period, you will always try to use subRule to select an available server. BestAvailableRule minimum concurrency strategy examines server one by one, if the server circuit breaker is turned on, ignore it, and then select the serverAvailabilityFilteringRule with the lowest concurrency links available filtering strategy to filter out the server that has been failed and marked as circuit tripped, to filter out the server with high concurrency links (active connections exceeds the configured threshold), or to use an AvailabilityPredicate to include the logic of filtering server, is to check the running status of each Server recorded in the status. ResponseTimeWeightedRule response time weighted weight strategy allocates weights according to the response time of server. The longer the response time is, the lower the weight is, and the lower the probability of being selected is. The shorter the response time, the higher the weight, and the higher the probability of being selected. This strategy is very appropriate and integrates various factors, such as network, disk, io, etc., all directly affect the response time ZoneAvoidanceRule region weight strategy to comprehensively judge the performance of the region where the server is located, and the availability of server, poll to select server and determine whether the running performance of an AWS Zone is available, and eliminate all server in the unavailable Zone.
Set load balancing policy
1. Coding mode
Write configuration classes in the Consumer service, using a random strategy
Package com.zt.consumer.config;import com.netflix.loadbalancer.IRule;import com.netflix.loadbalancer.RandomRule;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class MyRule {@ Bean public IRule rule () {return new RandomRule ();}}
Set the load balancing policy to be enabled for the specified service on the startup class, such as MyRule for EUREKA-PROVIDER.
Package com.zt.consumer;@SpringBootApplication@EnableEurekaClient@EnableDiscoveryClient/* configure Ribbon's load balancing policy name * name: set provider's application name * configuration: set load balancer Bean * / @ RibbonClient (name= "EUREKA-PROVIDER", configuration = MyRule.class) public class ConsumerApp {public static void main (String [] args) {SpringApplication.run (ConsumerApp.class, args);}}
two。 Configuration mode
# configuration method set Ribbon load balance policy EUREKA-PROVIDER: # set the service provider's application name ribbon: NFloadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule # policy class above is the meaning of load balance in Java Spring Cloud shared by Xiaobian. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, 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.
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.