负载均衡:Ribbon

spring cloud Ribbon是基于Netflix Ribbon实现的一套客户端,负载均衡工具。
简而言之,Ribbon是Netflix发布的开源项目,主要功能是提供客户端的软件负载均衡算法。
在这里插入图片描述

下面,将提供一个关于负载均衡的案例:

1.创建一个工程,导入相关依赖:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>

说明:如果在你创建的工程中已经导入过spring-cloud-starter-netflix-eureka-client的依赖,此步骤可以省略。如图:
在这里插入图片描述
2.为RestTemplate设置@LoadBalanced注解

package com.zyc.order;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableEurekaClient
@EnableHystrix
@EnableFeignClients
public class ServiceOrderApplication {
    
    

    public static void main(String[] args) {
    
    

        SpringApplication.run(ServiceOrderApplication.class, args);
    }

    @Bean
    @LoadBalanced  //实现负载均衡  ribbon
    public RestTemplate restTemplate() {
    
    
        return new RestTemplate();//httpClient
    }

}

这样,RestTemplate就具备了负载均衡的功能。

3.写service方法,实现ribbin

package com.zyc.order.service;

import com.zyc.order.entity.Order;
import com.zyc.order.entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Arrays;


@Service
public class OrderService {
    
    
    // Spring框架对RESTful方式的http请求做了封装,来简化操作  (底层 httpClient)
    @Autowired
    private RestTemplate restTemplate;
    public  Order createOrder(){
    
    
        //1.创建订单对象
        Order order= new Order();
        order.setOid(100010);
        order.setUid(3309);
        //2.调用商品服务--查询所有商品的信息----
        //Product[] productArray = restTemplate.getForObject("http://127.0.0.1:8081/product", Product[].class);

        Product[] productArray = restTemplate.getForObject("http://service-product/product", Product[].class);
        order.setProductList(Arrays.asList(productArray));
        //2.返回
        return order;
    }

运行测试如图:
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_47723535/article/details/109481608
今日推荐