Remote service invocation in spring cloud (2 ways)

Keywords: Spring Cloud Cloud Native

1, Remote service invocation based on RestTemplate object

Step 1: add the following method to the startup class of the service consumer to create the RestTemplate object

@Bean
public RestTemplate restTemplate(){//Implement remote service invocation based on this object
    return new RestTemplate();
}

Step 2: define the service consumer Controller layer and implement the remote service call within this object method

package com.jt.consumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


/**
 * Define the service consumer Controller in this Controller object
 * Implement the call to the remote service SCA provider
 */
@RestController
public class ConsumerController {
    /**
     * Get a RestTemplate object from the spring container,
     * Implement remote service invocation based on this object
     */
    @Autowired
    private RestTemplate restTemplate;
    /**
     * In this method, the service in the remote SCA provider is called through a RestTemplate object
     * @return
     * URL to access this method: http://localhost:8090/consumer/doRestEcho1
     */
    @GetMapping("/consumer/doRestEcho1")
    public String doRestEcho01(){
        //1. Define the url of the remote service to be called
        String url="http://localhost:8081/provider/echo/8090";
        //2. Call the service based on the relevant methods in the restTemplate object
        return restTemplate.getForObject(url, String.class);
    }

}

  Step 3: start the provider and consumer services respectively, and enter them in the browser http://localhost:8090/consumer/doRestEcho1 Address. If the access is successful, it will appear, as shown in the figure:

 

2, Feign based remote service invocation (key)

1. Background analysis
When the service consumer implements the remote service call based on the RestTemplate object, a direct way is to splice the url, splice the parameters, and then implement the service call. However, this splicing is required for each service call. The amount of code is complex and difficult to maintain. At this time, Feign was born.

2. What is feign?
Feign is a declarative Web service client. The bottom layer encapsulates the application of Rest technology. Feign can simplify the call and implementation of remote service provider methods by service consumers. As shown in the figure:


Feign was first maintained by Netflix. Later, Netflix no longer maintained feign. Finally, feign was maintained by some communities and renamed OpenFeign.

3.Feign application practice (mastery)

Step 1: add project dependencies on the service consumer (the SpringCloud team has developed the starter based on OpenFeign). The code is as follows:

 <!--Feign Medium API Encapsulates the remote service invocation mode and error mechanism-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

Step 2: add @ EnableFeignClients annotation on the service consumer startup class. The code is as follows:

/**
 * When the @ EnableFeignClients annotation is used to describe the configuration class, the main
 * Used to tell the spring framework to use the @ FeignClient annotation description
 * Create its implementation classes and objects
 */
@EnableFeignClients
@SpringBootApplication
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }

Step 3: in the service layer, define the Http request API. Based on this API, access the remote service with OpenFeign. The code is as follows:

package com.jt.consumer.service;

impor...

/**
 * @FeignClient Annotation describes the interface used to define the remote call specification
 * The value of the name attribute is the remote service name, which will also be used as the
 * RemoteProviderService The Bean name of the object of the interface implementation class
 */

@FeignClient(name = "sca-provider",contextId = "remoteProviderService")
public interface RemoteProviderService {
      /**
       * Remote service call based on this method
       * FAQ:
       * 1)Why write @ GetMapping annotation on the method?
       * Feign The interface is based on the value attribute value in @ GetMapping and other annotations on the method,
       * A specific method of the remote service will be called based on this value
       */
      @GetMapping("/provider/echo/{msg}")
      String echoMessage(@PathVariable("msg") String msg);
}

Note: the bottom layer of the interface described by @ FeignClient will automatically create an implementation class for it.

Step 4: create feign consumercontroller and add feign access. The code is as follows:

package com.jt.consumer.controller;

@RestController
@RequestMapping("/consumer")
public class FeignConsumerController {
    @Autowired
    private RemoteProviderService remoteProviderService;
    /**Service invocation based on feign mode*/
    @GetMapping("/echo/{msg}")
    public String doFeignEcho(@PathVariable  String msg){
        //Remote service invocation based on feign method (provided that the service must exist)
        return remoteProviderService.echoMessage(msg);
    }
}

Step 5: start the service and access it directly through feign client in the browser, as shown in the figure

3, Expansion: advanced practice of Feign configuration

https://blog.csdn.net/maitian_2008/article/details/118990381

4, Feign call procedure analysis (understand)


Feign application process analysis (understand the underlying logic first):
1) Tell springcloud through the @ EnableFeignCleints annotation to start the Feign Starter component.
2) Feign Starter will register the global configuration during the project startup, scan the interface described by @ feign client annotation under the package, then create the interface implementation class (JDK proxy class) at the bottom of the system, build the class object, and then hand it over to spring management (register the IOC container).
3) When the feign interface is called, it will be intercepted by the dynamic proxy class logic, and then the @ FeignClient Request information will be created through the encoder to make remote procedure calls based on this object.
4) Feign client request objects will be load balanced through the Ribbon to select a healthy Server instance.
5) Feign client will call the remote service with Request and return a response.
6) Feign client object parses the Response information and returns it to the client.
 

Posted by ChrisFlynn on Sat, 06 Nov 2021 02:22:16 -0700