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

How to use Ribbon and RestTemplate in SpringCloud to achieve service invocation and load balancing

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article is about how to use Ribbon and RestTemplate to achieve service invocation and load balancing in SpringCloud. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

SpringCloud is currently a leader in the field of micro-service architecture and is favored by developers and enterprises.

File directory structure

The file directory structure is important, with particular attention to the fact that the rule file needs to be placed one level above the main startup class before it can be scanned.

Write pom org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-actuator org.projectlombok lombok true org.springframework.boot Spring-boot-starter-test test org.springframework.cloud spring-cloud-starter-netflix-eureka-client

Because eureka's dependencies have integrated ribbon's dependencies, there is no need to introduce anything new.

Change ymlserver: port: 80spring: application: name: cloud-book-consumereureka: client: register-with-eureka: false fetch-registry: defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka main launch @ SpringBootApplication@EnableEurekaClient@RibbonClient (name = "CLOUD-BOOK-SERVICE") Configuration = LoadBalanceRule.class) / / change polling algorithm public class RestTemplateMain80 {public static void main (String [] args) {SpringApplication.run (RestTemplateMain80.class,args) }} Business Logic rules layer

Create a new LoadBalanceRule.class under the icon file directory to replace the load balancing algorithm.

@ Configurationpublic class LoadBalanceRule {@ Bean public IRule iRule () {/ / is defined as random return new RandomRule ();}} config layer

Enable restTemplate load balancing

Create a LoadBalanceConfig.class under the config folder

@ Configurationpublic class LoadBalanceConfig {@ Bean @ LoadBalanced / / enable load balancer public RestTemplate getReatTemplate () {return new RestTemplate ();}} controller layer

Create a new BookController.class

Write business code

@ RestController@Slf4jpublic class BookController {@ Resource private RestTemplate restTemplate; public static final String PAYMENT_URL = "http://CLOUD-BOOK-SERVICE"; @ GetMapping (value =" restTemplate/book/getAllBooks ") / / as long as json data is public CommonResult getAllBooks () {return restTemplate.getForObject (PAYMENT_URL+" / book/getAllBooks ", CommonResult.class) } @ GetMapping ("restTemplate/book/getAllBooks2") / / when you need to know more data, use the getForEntity method public CommonResult getAllBooks2 () {ResponseEntity resultResponseEntit = restTemplate.getForEntity (PAYMENT_URL+ "/ book/getAllBooks", CommonResult.class); if (resultResponseEntit.getStatusCode (). Is2xxSuccessful ()) {log.info (resultResponseEntit.getStatusCode () + "+ resultResponseEntit.getHeaders ()); return resultResponseEntit.getBody () } else {return new CommonResult (444, operation failed);} @ GetMapping (value = "restTemplate/book/index") public String index () {return restTemplate.getForObject (PAYMENT_URL+ "/ book/index", String.class);}}

Use restTemplate+Ribboin to implement service invocation and load balancing.

Handwritten Ribbon load balancing algorithm lb layer 1. Create a new LoadBalancer interface and add the code public interface LoadBalancer {ServiceInstance instances (List serviceInstances);} 2. Create a new implementation class MyLB@Componentpublic class MyLB implements LoadBalancer {private AtomicInteger atomicInteger = new AtomicInteger (0); / / find how many times to access the spin lock thought public final int getAndIncrement () {int current; int next; do {current = this.atomicInteger.get (); next = current > = 2147483647? 0: current+1;} while (! this.atomicInteger.compareAndSet (current,next)) System.out.println ("* visit next- >" + next); return next;} / / load balancing algorithm, implement roundRobin algorithm @ Override public ServiceInstance instances (List serviceInstances) {int index = getAndIncrement ()% serviceInstances.size (); return serviceInstances.get (index);}} modify BookController@RestController@Slf4jpublic class BookController {@ Resource private RestTemplate restTemplate; @ Resource private LoadBalancer loadBalancer @ Resource private DiscoveryClient discoveryClient; public static final String PAYMENT_URL = "http://CLOUD-BOOK-SERVICE"; @ GetMapping (value =" restTemplate/book/getAllBooks ") / / as long as json data is public CommonResult getAllBooks () {List instances = discoveryClient.getInstances (" CLOUD-BOOK-SERVICE "); if (instances = = null | | instances.size ()

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

Development

Wechat

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

12
Report