SpringCloud Ribbon负载均衡代码实例

 更新时间:2020年03月13日 11:46:13   作者:玉天恒  
这篇文章主要介绍了SpringCloud Ribbon负载均衡代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

1.添加依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
  <dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>

<!-- lombok -->
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <optional>true</optional>
</dependency>

2.修改启动类

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@MapperScan("cn.ytheng.order_service")
public class OrderServiceApplication {

  /**
   * @Loadbalanced负载均衡策略
   */
  @Bean
  @LoadBalanced
  public RestTemplate restTemplate() {
    return new RestTemplate();
  }

  public static void main(String[] args) {

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

}

3.添加Controller

import cn.theng.order_service.utils.RibbonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/order")
public class ProductOrderController {

  @RequestMapping("/test")
  public Object test(@RequestParam("product_id") int productId) {

    //方法一
//    ServiceInstance instance = loadBalancerClient.choose("product-service");
//    String url = String.format("http://%s:%s/api/v1/product/find?id=" + productId, instance.getHost(), instance.getPort());
//    RestTemplate template = new RestTemplate();
//    Map<String, Object> map2 = template.getForObject(url, Map.class);

    //负载均衡
    //商品列表启用两个节点时
    //由客户端来自动选择节点,可能是8771端口,也有可能是8772端口
    //参数id名称需要保持一致
    //方法二(推荐)
    String uri = "http://product-service/api/v1/product/find?id={id}";
    Map<String, Object> request = new HashMap<>();
    request.put("id", productId);
    Map<String, Object> map3 = RibbonUtils.get(uri, Map.class, request);

    return "success";
  }

  @PostMapping("/test2")
  public Object test2(@RequestParam("product_id") int productId) {

    Product product = new Product();
    product.setId(productId);

    String uri = "http://product-service/api/v1/product/find2";
    LinkedMultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("token", "theng");
    Object result = RibbonUtils.post(uri, Object.class, product, headers);

    return "success";
  }
}

4.添加Ribbon调用公共类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;

@Component
public class RibbonUtils {

  @Autowired
  private RestTemplate restTemplate;

  private static RestTemplate template;

  //@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次
  @PostConstruct
  public void init() {
    template = restTemplate;
  }

  /**
   *
   * @param uri 接口地址
   * @param responseType 返回类型
   *
   * */
  public static <T> T get(String uri, Class<T> responseType) {

    return template.getForObject(uri, responseType);
  }

  /**
   *
   * @param uri 接口地址
   * @param responseType 返回类型
   * @param request 传递参数
   *
   * */
  public static <T> T get(String uri, Class<T> responseType, Map<String, ?> request) {

    return template.getForObject(uri, responseType, request);
  }

  /**
   *
   * @param uri 接口地址
   * @param responseType 返回类型
   * @param request 传递参数
   * @param headerMap 报头信息
   *
   * */
  public static <T> T get(String uri, Class<T> responseType, Map<String, ?> request, Map<String, String> headerMap) {

    //添加报头
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    for(Map.Entry<String, String> entry : headerMap.entrySet()){
      String mapKey = entry.getKey();
      String mapValue = entry.getValue();
      headers.add(mapKey, mapValue);
    }

    //body的类型定为String,这里使用get没有用到body,post会使用到
    HttpEntity<String> entity = new HttpEntity<String>(null, headers);

    ResponseEntity<T> result = template.exchange(uri, HttpMethod.GET, entity, responseType, request);

    return result.getBody();
  }

  /**
   *
   * @param uri 接口地址
   * @param responseType 返回类型
   * @param body 传递实体
   * @param headers 报头信息
   *
   * */
  public static <T> T post(String uri, Class<T> responseType, Object body, LinkedMultiValueMap<String, String> headers) {

    if (!headers.containsKey("Content-Type")) {
      headers.put("Content-Type", Collections.singletonList("application/json;charset=UTF-8"));
    }

    HttpEntity request = new HttpEntity(body, headers);
    Object obj = template.postForObject(uri, request, responseType);
    return (T) obj;
  }
}

5.在PostMan上测试两个接口即可

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Spring IOC xml方式进行工厂Bean操作详解

    Spring IOC xml方式进行工厂Bean操作详解

    这篇文章主要介绍了Spring IOC xml方式进行工厂Bean操作,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习吧
    2023-01-01
  • Java通过Fork/Join优化并行计算

    Java通过Fork/Join优化并行计算

    这篇文章主要为大家详细介绍了Java通过Fork、Join来优化并行计算,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-04-04
  • SpringBoot集成Kafka 配置工具类的详细代码

    SpringBoot集成Kafka 配置工具类的详细代码

    spring-kafka 是基于 java版的 kafka client与spring的集成,提供了 KafkaTemplate,封装了各种方法,方便操作,它封装了apache的kafka-client,不需要再导入client依赖,这篇文章主要介绍了SpringBoot集成Kafka 配置工具类,需要的朋友可以参考下
    2022-09-09
  • SpringBoot+MybatisPlus+Mysql+JSP实战

    SpringBoot+MybatisPlus+Mysql+JSP实战

    这篇文章主要介绍了SpringBoot+MybatisPlus+Mysql+JSP实战,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-12-12
  • java打印国际象棋棋盘的方法

    java打印国际象棋棋盘的方法

    这篇文章主要为大家详细介绍了java打印出国际象棋棋盘的相关代码,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-05-05
  • 详解Maven profile配置管理及激活profile的几种方式

    详解Maven profile配置管理及激活profile的几种方式

    这篇文章主要介绍了详解Maven profile配置管理及激活profile的几种方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01
  • 使用IDEA画UML图的详细步骤

    使用IDEA画UML图的详细步骤

    UML是面向对象设计的建模工具,独立于任何具体程序设计语言,是一种为面向对象系统的产品进行说明、可视化和编制文档的一种标准语言,本文重点给大家介绍使用IDEA画UML图的详细步骤,需要的朋友参考下吧
    2021-06-06
  • 手把手教你在eclipse创建第一个java web项目并运行

    手把手教你在eclipse创建第一个java web项目并运行

    Eclipse是用来做开发的自由集成开发环境,这也是很多java程序员会使用的开发环境,所以可以使用eclipse创建javaweb项目,下面这篇文章主要给大家介绍了关于如何在eclipse创建第一个java web项目并运行的相关资料,需要的朋友可以参考下
    2023-02-02
  • Intellij IDEA中启动多个微服务(开启Run Dashboard管理)

    Intellij IDEA中启动多个微服务(开启Run Dashboard管理)

    这篇文章主要介绍了Intellij IDEA中启动多个微服务(开启Run Dashboard管理),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-07-07
  • Mybatis中的延迟加载,以及原理分析

    Mybatis中的延迟加载,以及原理分析

    这篇文章主要介绍了Mybatis中的延迟加载以及原理,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-04-04

最新评论