springcloud中Ribbon和RestTemplate實(shí)現(xiàn)服務(wù)調(diào)用與負(fù)載均衡
文件目錄結(jié)構(gòu)

文件目錄結(jié)構(gòu)很重要,特別注意的是rule文件要放在主啟動類上一級位置,才能夠掃描。
寫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>
因為eureka的依賴已經(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
主啟動
@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ù)時
public CommonResult getAllBooks(){
return restTemplate.getForObject(PAYMENT_URL+"/book/getAllBooks",CommonResult.class);
}
@GetMapping("restTemplate/book/getAllBooks2") //需要知道更多數(shù)據(jù)時,使用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ù)時
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);
}
}
修改文件注解
- 刪去主啟動類的更換負(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ù)項目案例解析
- 關(guān)于springboot 中使用httpclient或RestTemplate做MultipartFile文件跨服務(wù)傳輸?shù)膯栴}
- restTemplate未設(shè)置連接數(shù)導(dǎo)致服務(wù)雪崩問題以及解決
相關(guān)文章
MyBatis動態(tài)<if>標(biāo)簽使用避坑指南
這篇文章主要為大家介紹了MyBatis動態(tài)<if>標(biāo)簽使用避坑指南,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03
Java?IO篇之Reactor?網(wǎng)絡(luò)模型的概念
Reactor?模式也叫做反應(yīng)器設(shè)計模式,是一種為處理服務(wù)請求并發(fā)提交到一個或者多個服務(wù)處理器的事件設(shè)計模式,Reactor?模式主要由?Reactor?和處理器?Handler?這兩個核心部分組成,本文給大家介紹Java?IO篇之Reactor?網(wǎng)絡(luò)模型的概念,感興趣的朋友一起看看吧2022-01-01
Java算法實(shí)戰(zhàn)之排一億個隨機(jī)數(shù)
我們在生活中經(jīng)常遇見一些這樣的需求,隨機(jī)點(diǎn)名、公司年會抽獎、微信拼手氣紅包等,還有一些游戲比如打地鼠小游戲、俄羅斯方塊等,這些場景中都會用到一種算法:隨機(jī),這篇文章主要給大家介紹了關(guān)于Java算法實(shí)戰(zhàn)之排一億個隨機(jī)數(shù)的相關(guān)資料,需要的朋友可以參考下2021-11-11
Java+opencv3.2.0實(shí)現(xiàn)輪廓檢測
這篇文章主要為大家詳細(xì)介紹了Java+opencv3.2.0實(shí)現(xiàn)輪廓檢測,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-07-07

