springcloud (4) is called between the common micro-services

 

table of Contents

Called between the commonly used micro-services

RPC:

 Rest(Http):

ribbon merchandise orders call service

Custom load balancing strategy:

feign way to achieve inter-call service

Feign way call between the core and the source code interpretation service ribbon, feign selection


 

 


 

Called between the commonly used micro-services

RPC:

              Remote procedure calls, such as calling a local service (method) call the server the same service

              It supports synchronous, asynchronous calls

      Establishing a TCP connection between the client and the server, you can set up a time, but also a multiplex link (a connection time-consuming) and more large companies can use multiple RPC calls

              PRC small packets

                     protobuf

                     thrift

              rpc: codec, serialization, links, packet loss, protocol (large costs)

 Rest(Http):

              http request, support for multiple protocols and functions

              Facilitate the development of low cost

              http packets large

              java development: HttpClient, URLConnection

spring cloud temporarily in this way


ribbon merchandise orders call service


       1. Create a project order_service

       2, the development of a pseudo-single Interface

       3, using a ribbon. (Similar httpClient, URLConnection) packing more stuff

                     Start class adds comment

                       @Bean

                       @LoadBalanced

                       Template Residual public rest template () {

                            return new RestTemplate();

                       }

       4, call by name merchandise, Getting product details

Get product-service from the list of eureka in the (registered in the name of the yml)

 


 

Ribbon source code analysis

Analysis @LoadBalanced

              1) First, get a list from the registry provider

              2) by selecting a certain strategy wherein a node

              3) back to the calling restTemplate

 Want to find the service name

   Get a list of product-service

(Default policy)

serviceId(product-service)


Custom load balancing strategy:

http://cloud.spring.io/spring-cloud-static/Finchley.RELEASE/single/spring-cloud.html#_customizing_the_ribbon_client_by_setting_properties

In the configuration file yml inside, custom load balancing strategy

              # Custom load balancing strategy

              product-service: (registered service name're looking for call center services strategy which can have many services each service has a corresponding strategy)

                ribbon:

                  NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

Strategies:

       1, the same as if each machine configuration, it is recommended not to modify the policy (recommended)

       2, if the strong part of the machine configuration, you can instead WeightedResponseTimeRule (see IRule implementation class)


feign way to achieve inter-call service


Renovation project electricity supplier orders for service calls Goods Services get product information

 Feign: pseudo-RPC client (or nature with http)

       官方文档: https://cloud.spring.io/spring-cloud-openfeign/

       1、使用feign步骤讲解(新旧版本依赖名称不一样)

              加入依赖                    

  <dependency>

       <groupId>org.springframework.cloud</groupId>

       <artifactId>spring-cloud-starter-openfeign</artifactId>

  </dependency>

                     启动类增加@EnableFeignClients

                     增加一个接口 并@FeignClient(name="product-service")

官文

@SpringBootApplication
@EnableFeignClients
public class WebApplication {

	public static void main(String[] args) {
		SpringApplication.run(WebApplication.class, args);
	}

	@FeignClient("name")
	static interface NameService {
		@RequestMapping("/")
		public String getName();
	}
}

       2、编码实战

@FeignClient(name="product-service")
public interface ProductClients {
    @GetMapping("/api/v1/product/find")
    String findById(@RequestParam(value = "id")int id);

}
   @Resource
    ProductClients productClients;

    @Override
    public ProductOrder save(int userId, int productId) {
        //Object object = restTemplate.getForObject("http://product-service/api/v1/product/find?id=" + productId, Object.class);
        // System.out.println(object);
        //  Map<String,Object> productMap = restTemplate.getForObject("http://product-service/api/v1/product/find?id=" + productId, Map.class);
        String response = productClients.findById(productId);
        JsonNode jsonNode = JsonUtil.str2JsonNode(response);


        ProductOrder productOrder = new ProductOrder();
        productOrder.setCreateTime(new Date());
        productOrder.setTradeNo(UUID.randomUUID().toString());
        productOrder.setUserId(userId);productOrder.setPrice(Integer.parseInt(jsonNode.get("price").toString()) );
        productOrder.setProductName(jsonNode.get("name").toString());

        return productOrder;
    }

       3、注意点:

              1、路径     (要和调用方product-service的路由保持一致)

                    @FeignClient(name="product-service") 要和保持一致

              2、Http方法必须对应 

              3、使用requestBody,应该使用@PostMapping

               

              4、多个参数的时候,通过@RequestParam("id") int id)方式调用

                       "id"要和(int id)保持一致


Feign核心源码解读和 服务间的调用方式ribbon、feign选择


       1、ribbon和feign两个的区别和选择

              选择feign

                     默认集成了ribbon

                     写起来更加思路清晰和方便

                     采用注解方式进行配置,配置熔断等方式方便 

       2、超时配置

              默认options readtimeout是60,但是由于hystrix默认是1秒超时

              #修改调用超时时间  

                     feign:

                       client:

                         config:

                           default:

                             connectTimeout: 2000

                             readTimeout: 2000

                     模拟接口响应慢,线程睡眠新的方式

                       try {

                          TimeUnit.SECONDS.sleep(1);

                      } catch (InterruptedException e) {

                          e.printStackTrace();

                      }

 


 

Guess you like

Origin blog.csdn.net/qq_29235677/article/details/91994857