您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關SpringCloud中怎么使用Ribbon和RestTemplate實現服務調用和負載平衡的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
SpringCloud 是目前微服務架構領域的翹楚,備受開發者和企業的青睞。
文件目錄結構很重要,特別注意的是rule文件要放在主啟動類上一級位置,才能夠掃描。
<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的依賴已經整合了ribbon的依賴,所以不用額外引入新的東西。
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);
}
}
在圖示文件目錄下新建LoadBalanceRule.class,用于更換負載均衡算法。
@Configuration
public class LoadBalanceRule {
@Bean
public IRule iRule() {
// 定義為隨機
return new RandomRule();
}
}
開啟restTemplate負載均衡
在config文件夾下創建LoadBalanceConfig.class
@Configuration
public class LoadBalanceConfig {
@Bean
@LoadBalanced //開啟負載均衡
public RestTemplate getReatTemplate(){
return new RestTemplate();
}
}
新建BookController.class
寫業務代碼
@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數據時
public CommonResult getAllBooks(){
return restTemplate.getForObject(PAYMENT_URL+"/book/getAllBooks",CommonResult.class);
}
@GetMapping("restTemplate/book/getAllBooks2") //需要知道更多數據時,使用getForEntity方法
public CommonResult getAllBooks2(){
ResponseEntity<CommonResult> 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,"操作失敗");
}
}
@GetMapping(value = "restTemplate/book/index")
public String index() {
return restTemplate.getForObject(PAYMENT_URL+"/book/index",String.class);
}
}
使用restTemplate+Ribboin實現服務調用和負載均衡完成。
public interface LoadBalancer {
ServiceInstance instances(List<ServiceInstance> serviceInstances);
}
@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;
}
//負載均衡算法,實現roundRobin算法
@Override
public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
int index = getAndIncrement() % serviceInstances.size();
return serviceInstances.get(index);
}
}
@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數據時
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);
}
}
刪去主啟動類的更換負載均衡算法注解
@RibbonClient(name = “CLOUD-BOOK-SERVICE”, configuration = LoadBalanceRule.class)
刪去LoadBalanceConfig中開啟負載均衡算法注解
@LoadBalanced
手寫Ribbon算法并使用完成
感謝各位的閱讀!關于“SpringCloud中怎么使用Ribbon和RestTemplate實現服務調用和負載平衡”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。