1.OpenFeign

When accessing the remote interface using the restTemplate, it is difficult to manage the interface, and we may make multiple changes when the interface changes. Spring Cloud provides OpenFeign to solve this problem.

2. Import dependencies

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
Copy the code

3. Configure the parameters accordingly

Public DemoApplication {public static void main(String[] args) {public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }}Copy the code

4. Access request

/ / name: @component@feignClient (name = "demoprovider-server") public interface DemoProvideFeignClient { @getMapping ("/demo/text")// The access path does not need to carry the requested address Result create(); }Copy the code
  @GetMapping("/create")
    public Result test(a){
        return ResultHelper.newSuccessResult(
                demoProvideFeignClient.create());
    }
Copy the code

5. Use a browserhttp://localhost:8080/create

{"code":200, "MSG ":" demo access successful ", "data":null}Copy the code

6. There are problems

When the service provider service is down or has access problems, the current service cannot detect corresponding errors and judge.

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Tue Mar 02 13:40:33 CST 2021
There was an unexpected error (type=Internal Server Error, status=500).
Copy the code

Solution: Hystrix==

Hystrix is used for fusing and Openfeign is used for other processing when access to third-party services times out

7. Fusing treatment

// Import dependencies<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
Copy the code
// Add annotations
@EnableHystrix
public class DemoApplication {}Copy the code
/ / need to fuse processing methods add / / testTimeOutFallbackMethod is fusing with the object returned @ HystrixCommand (fallbackMethod = "testTimeOutFallbackMethod",commandProperties = { @HystrixProperty(name = "Execution. The isolation. Thread. TimeoutInMilliseconds," value = "1500") / /} is normal business logic within 3 seconds) public Result method () {XXX XXX xxx return result; } eg: public Result testTimeOutFallbackMethod (Throwable) e) {return ResultHelper. NewErrorResult (101, "call the service failure"); }Copy the code
  1. Use the browser to access the corresponding url, feignClient when visiting another micro service if the request timeout will perform testTimeOutFallbackMethod returns
{
"code":101."msg":"Service invocation failed"."data":null
}
Copy the code

The end of the