[Spring cloud step by step implementation of the ad system] 11. Use Feign implement micro service calls

On the one we used Ribbon (based Http/Tcp) micro-call service, call the Ribbon is relatively simple, intercepts the request service through Ribbon components, by Eureka Serveracquiring the service instance IP:Port, and then go call the API. This lesson we use a simpler way to achieve, using declarative Webservices client Feign, we only need to use Feign to declare an interface, use 注解for configuration can be used, it is not very simple? The actual work, we will only use Feign to make the call (most) between services. Next, we operate an instance.

In order to reuse the code, we create a new project mscx-ad-feign-sdkas a service tool Feign's call.

  • Create a projectmscx-ad-feign-sdk
  • Trilogy Step 1 (plus dependent)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>mscx-ad</artifactId>
        <groupId>com.sxzhongf</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <packaging>jar</packaging>
    <name>mscx-ad-feign-sdk</name>
    <description>只定义微服务Feign调用用到的请求对象和响应对象,而不涉及具体的实现类。</description>

    <groupId>com.sxzhongf</groupId>
    <artifactId>mscx-ad-feign-sdk</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 引入服务调用的组件 feign 依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>com.sxzhongf</groupId>
            <artifactId>mscx-ad-common</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <!-- 引入系统容错hystrix 的依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
            <version>1.2.7.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
  • Trilogy Step 2 (plus annotations @EnableFeignClients, add in specific micro-services using our custom FeignClient)
/**
 * ISponsorFeignClient for service using
 *
 * @author <a href="mailto:[email protected]">Isaac.Zhang | 若初</a>
 */
@FeignClient(value = "mscx-ad-sponsor", fallback = SponsorClientHystrix.class)
public interface ISponsorFeignClient {
    @RequestMapping(value = "/ad-sponsor/plan/get", method = RequestMethod.POST)
    CommonResponse<List<AdPlanVO>> getAdPlansUseFeign(@RequestBody AdPlanGetRequestVO requestVO);

    @RequestMapping(value = "/ad-sponsor/user/get", method = RequestMethod.GET)
    /**
     * Feign 埋坑之 如果是Get请求,必须在所有参数前添加{@link RequestParam},不能使用{@link Param}
     * 会被自动转发为POST请求。
     */
    CommonResponse getUsers(@RequestParam(value = "username") String username);
}


---
@RestController
@Slf4j
@RequestMapping(path = "/search-feign")
public class SearchFeignController {
   /**
   * 注入我们自定义的FeignClient
   */
    private final ISponsorFeignClient sponsorFeignClient;
    @Autowired
    public SearchFeignController(ISponsorFeignClient sponsorFeignClient) {
        this.sponsorFeignClient = sponsorFeignClient;
    }

    @GetMapping(path = "/user/get")
    public CommonResponse getUsers(@Param(value = "username") String username) {
        log.info("ad-search::getUsersFeign -> {}", JSON.toJSONString(username));
        CommonResponse commonResponse = sponsorFeignClient.getUsers(username);
        return commonResponse;
    }
}
  • Trilogy Step 3 (plus configuration tool library does not need to add the specific micro service)

Examples of the above we have a problem, if our advertising service there is a problem, then we call by using the API FeignClient sponsorFeignClient.getUsers(username);'ll get an error if the error for a long time, can cause large-scale service error problem, there is also we often say that the avalanche effect service, we want a service error and how to avoid problems caused the collapse of the entire system? Here we need to introduce a component Hystrixto handle service error.

  • Trilogy Step1 (plus dependent)
    UTOOLS1564468068440.png

We can see from the chart, we introduce Feign rely on when it itself has relied Hystrix, according to Maven dependent transitive, we can know our own service already includes support Hystrix dependent, we can directly use the ~

  • Trilogy Step2 (annotated) @EnableHystrix // 开启hystrix 断路器
  • Trilogy Step3 (configuration change)
feign:
  hystrix:
    enabled: true
  • Feign Hystrix use to configure a fault-tolerant implementation calls
@Component
public class SponsorClientHystrix implements ISponsorFeignClient {
    @Override
    public CommonResponse<List<AdPlanVO>> getAdPlansUseFeign(AdPlanGetRequestVO requestVO) {
        return new CommonResponse<>(-1, "mscx-ad-sponsor feign & hystrix get plan error.");
    }

    @Override
    public CommonResponse getUsers(String username) {
        return new CommonResponse<>(-1, "mscx-ad-sponsor feign & hystrix get user error.");
    }
}

In ISponsorFeignClientclass, add error handling class (fallback)

@FeignClient(value = "mscx-ad-sponsor", fallback = SponsorClientHystrix.class)
public interface ISponsorFeignClient {
...

In SponsorClientHystrix, we pay special attention to 2:00

  1. The class must add @Componentannotations to be added to the Spring container
  2. This class needs to implement ISponsorFeignClientFeign client interface

Through the above realization, our services during the call, if an error occurs, the service will be downgraded to call the default method of error handling class should be called in, it achieved a short-circuit processing we want to do to protect our the current service.

Guess you like

Origin www.cnblogs.com/zhangpan1244/p/11300420.html