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.컨트롤 러 추가

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.리본 추가

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 에서 두 개의 인 터 페 이 스 를 테스트 하면 된다

이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기