App下載

SpringCloud中如何使用Ribbon和RestTemplate實現(xiàn)服務調(diào)用和負載平衡

猿友 2021-08-04 11:28:59 瀏覽數(shù) (1900)
反饋

SpringCloud 是目前微服務架構領域的翹楚,備受開發(fā)者和企業(yè)的青睞。下面,我將介紹 SpringCloud 中是如何使用 Ribbon 工具框架和 RestTemplate 模板類來實現(xiàn)服務調(diào)用和負載平衡。

文件目錄結構

202148100124156

文件目錄結構很重要,特別注意的是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è)務邏輯

rules層

在圖示文件目錄下新建LoadBalanceRule.class,用于更換負載均衡算法。

@Configuration
public class LoadBalanceRule {
    @Bean
    public IRule iRule() {
        // 定義為隨機
        return new RandomRule();
    }
}

config層

開啟restTemplate負載均衡
在config文件夾下創(chuàng)建LoadBalanceConfig.class

@Configuration
public class LoadBalanceConfig {
    @Bean
    @LoadBalanced            //開啟負載均衡
    public RestTemplate getReatTemplate(){
        return new RestTemplate();
    }
}

controller層

新建BookController.class
寫業(yè)務代碼

@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()+"	"+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實現(xiàn)服務調(diào)用和負載均衡完成。

手寫Ribbon負載均衡算法 lb層

1.新建LoadBalancer接口,添加代碼

public interface LoadBalancer {
    ServiceInstance instances(List<ServiceInstance> serviceInstances);
}

2.新建實現(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;
    }

    //負載均衡算法,實現(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);
    }
}

修改文件注解

  • 刪去主啟動類的更換負載均衡算法注解

@RibbonClient(name = “CLOUD-BOOK-SERVICE”, configuration = LoadBalanceRule.class)

  • 刪去LoadBalanceConfig中開啟負載均衡算法注解

@LoadBalanced

手寫Ribbon算法并使用完成

以上就是 Spring Cloud 中使用 Ribbon 和 RestTemplate 實現(xiàn)服務調(diào)用與負載均衡的詳細內(nèi)容,想要了解更多關于 Spring Cloud 中的 Ribbon 和 RestTemplate 服務與負載的資料,請關注W3Cschool其它相關文章!


0 人點贊