springcloud中Ribbon和RestTemplate實(shí)現(xiàn)服務(wù)調(diào)用與負(fù)載均衡
文件目錄結(jié)構(gòu)
文件目錄結(jié)構(gòu)很重要,特別注意的是rule文件要放在主啟動(dòng)類上一級位置,才能夠掃描。
寫pom
<dependencies> <!--springboot 2.2.2--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--Spring cloud Hoxton.SR1--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!--Spring cloud alibaba 2.1.0.RELEASE--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--Eureka-Client--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
因?yàn)閑ureka的依賴已經(jīng)整合了ribbon的依賴,所以不用額外引入新的東西。
改yml
server: port: 80 spring: application: name: cloud-book-consumer eureka: client: register-with-eureka: false fetch-registry: true service-url: defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
主啟動(dòng)
@SpringBootApplication @EnableEurekaClient @RibbonClient(name = "CLOUD-BOOK-SERVICE", configuration = LoadBalanceRule.class) //更換輪詢算法 public class RestTemplateMain80 { public static void main(String[] args) { SpringApplication.run(RestTemplateMain80.class,args); } }
業(yè)務(wù)邏輯
rules層
在圖示文件目錄下新建LoadBalanceRule.class,用于更換負(fù)載均衡算法。
@Configuration public class LoadBalanceRule { @Bean public IRule iRule() { // 定義為隨機(jī) return new RandomRule(); } }
config層
開啟restTemplate負(fù)載均衡
在config文件夾下創(chuàng)建LoadBalanceConfig.class
@Configuration public class LoadBalanceConfig { @Bean @LoadBalanced //開啟負(fù)載均衡 public RestTemplate getReatTemplate(){ return new RestTemplate(); } }
controller層
新建BookController.class
寫業(yè)務(wù)代碼
@RestController @Slf4j public class BookController { @Resource private RestTemplate restTemplate; public static final String PAYMENT_URL = "http://CLOUD-BOOK-SERVICE"; @GetMapping(value = "restTemplate/book/getAllBooks")//只要json數(shù)據(jù)時(shí) public CommonResult getAllBooks(){ return restTemplate.getForObject(PAYMENT_URL+"/book/getAllBooks",CommonResult.class); } @GetMapping("restTemplate/book/getAllBooks2") //需要知道更多數(shù)據(jù)時(shí),使用getForEntity方法 public CommonResult getAllBooks2(){ ResponseEntity<CommonResult> resultResponseEntit = restTemplate.getForEntity(PAYMENT_URL+"/book/getAllBooks",CommonResult.class); if (resultResponseEntit.getStatusCode().is2xxSuccessful()){ log.info(resultResponseEntit.getStatusCode()+"\t"+resultResponseEntit.getHeaders()); return resultResponseEntit.getBody(); }else { return new CommonResult<>(444,"操作失敗"); } } @GetMapping(value = "restTemplate/book/index") public String index() { return restTemplate.getForObject(PAYMENT_URL+"/book/index",String.class); } }
使用restTemplate+Ribboin實(shí)現(xiàn)服務(wù)調(diào)用和負(fù)載均衡完成。
手寫Ribbon負(fù)載均衡算法 lb層
1.新建LoadBalancer接口,添加代碼
public interface LoadBalancer { ServiceInstance instances(List<ServiceInstance> serviceInstances); }
2.新建實(shí)現(xiàn)類MyLB
@Component public class MyLB implements LoadBalancer { private AtomicInteger atomicInteger = new AtomicInteger(0); //求第幾次訪問 自旋鎖思想 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("***第幾次訪問next->"+next); return next; } //負(fù)載均衡算法,實(shí)現(xiàn)roundRobin算法 @Override public ServiceInstance instances(List<ServiceInstance> serviceInstances) { int index = getAndIncrement() % serviceInstances.size(); return serviceInstances.get(index); } }
修改BookController
@RestController @Slf4j public 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")//只要json數(shù)據(jù)時(shí) public CommonResult getAllBooks(){ List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-BOOK-SERVICE"); if (instances == null || instances.size() <= 0){ return null; } ServiceInstance serviceInstance = loadBalancer.instances(instances); URI uri = serviceInstance.getUri(); return restTemplate.getForObject(uri+"/book/getAllBooks",CommonResult.class); } @GetMapping(value = "restTemplate/book/index") public String index() { List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-BOOK-SERVICE"); if (instances == null || instances.size() <= 0){ return null; } ServiceInstance serviceInstance = loadBalancer.instances(instances); URI uri = serviceInstance.getUri(); return restTemplate.getForObject(uri+"/book/index",String.class); } }
修改文件注解
- 刪去主啟動(dòng)類的更換負(fù)載均衡算法注解
@RibbonClient(name = “CLOUD-BOOK-SERVICE”, configuration = LoadBalanceRule.class)
- 刪去LoadBalanceConfig中開啟負(fù)載均衡算法注解
@LoadBalanced
手寫Ribbon算法并使用完成
以上就是Ribbon和RestTemplate實(shí)現(xiàn)服務(wù)調(diào)用與負(fù)載均衡的詳細(xì)內(nèi)容,更多關(guān)于Ribbon和RestTemplate服務(wù)與負(fù)載的資料請關(guān)注腳本之家其它相關(guān)文章!
- restTemplate實(shí)現(xiàn)跨服務(wù)API調(diào)用方式
- Spring?Cloud?Alibaba?Nacos服務(wù)治理平臺服務(wù)注冊、RestTemplate實(shí)現(xiàn)微服務(wù)之間訪問負(fù)載均衡訪問的問題
- Java服務(wù)調(diào)用RestTemplate與HttpClient的使用詳解
- SpringCloud基于RestTemplate微服務(wù)項(xiàng)目案例解析
- 關(guān)于springboot 中使用httpclient或RestTemplate做MultipartFile文件跨服務(wù)傳輸?shù)膯栴}
- restTemplate未設(shè)置連接數(shù)導(dǎo)致服務(wù)雪崩問題以及解決
相關(guān)文章
springboot如何接收application/x-www-form-urlencoded類型的請求
這篇文章主要介紹了springboot如何接收application/x-www-form-urlencoded類型的請求,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11聊聊注解@Aspect的AOP實(shí)現(xiàn)操作
這篇文章主要介紹了聊聊注解@Aspect的AOP實(shí)現(xiàn)操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01Java中Lambda表達(dá)式之Lambda語法與作用域解析
這篇文章主要介紹了Java中Lambda表達(dá)式之Lambda語法與作用域解析重點(diǎn)介紹Lambda表達(dá)式基礎(chǔ)知識,需要的朋友可以參考下2017-02-02HashMap和List遍歷方法及如何遍歷刪除元素總結(jié)
在本篇文章中小編給大家分享了關(guān)于HashMap和List遍歷方法及如何遍歷刪除元素知識點(diǎn)總結(jié),需要的朋友們參考下。2019-05-05java遞歸實(shí)現(xiàn)復(fù)制一個(gè)文件夾下所有文件功能
這篇文章主要介紹了java遞歸實(shí)現(xiàn)復(fù)制一個(gè)文件夾下所有文件功能n次,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-08-08