Feign用于一个微服务子系统调用另一个微服务子系统的接口,本质就是http请求。但是我们的微服务都是受保护的,没有合法的令牌是无法获取到数据的,并且Fein默认并不会帮我们传递令牌。
    综于上述原因,这里有必要提及下当前系统中Feign的使用方式。
    假如现在需要在qingfeng-server-hello系统中调用qingfeng-server-system系统中的TestController中的/hello接口数据,我们需要在qingfeng-server-hello系统中进行如下操作:
    1、系统入口类上添加@EnableFeignClients注解;
    咱们的系统需要增加:@EnableCloudApplication 因为在【@EnableCloudApplication】中包含了@EnableFeignClients的注解。
    2、系统配置文件中添加如下配置:

    1. feign:
    2. hystrix:
    3. enabled: true
    4. hystrix:
    5. shareSecurityContext: true


    3、编写IHelloService:

    @FeignClient(value = ServerConstant.QINGFENG_SERVER_SYSTEM, contextId = “helloServiceClient”, fallbackFactory = HelloServiceFallback.class)

    1. package com.qingfeng.service;
    2. import com.qingfeng.entity.ServerConstant;
    3. import com.qingfeng.service.fallback.HelloServiceFallback;
    4. import org.springframework.cloud.openfeign.FeignClient;
    5. import org.springframework.web.bind.annotation.GetMapping;
    6. import org.springframework.web.bind.annotation.RequestParam;
    7. /**
    8. * @author Administrator
    9. * @version 1.0.0
    10. * @ProjectName qingfeng-cloud
    11. * @Description TODO
    12. * @createTime 2021年04月19日 14:44:00
    13. */
    14. @FeignClient(value = ServerConstant.QINGFENG_SERVER_SYSTEM, contextId = "helloServiceClient", fallbackFactory = HelloServiceFallback.class)
    15. public interface IHelloService {
    16. @GetMapping("hello")
    17. public String hello(@RequestParam("name") String name);
    18. }

    4、编写HelloServiceFallback

    1. package com.qingfeng.service.fallback;
    2. import com.qingfeng.service.IHelloService;
    3. import feign.hystrix.FallbackFactory;
    4. import lombok.extern.slf4j.Slf4j;
    5. import org.springframework.stereotype.Component;
    6. /**
    7. * @ProjectName HelloServiceFallback
    8. * @author Administrator
    9. * @version 1.0.0
    10. * @Description TODO
    11. * @createTime 2021/4/19 0019 14:45
    12. */
    13. @Slf4j
    14. @Component
    15. public class HelloServiceFallback implements FallbackFactory<IHelloService> {
    16. @Override
    17. public IHelloService create(final Throwable throwable) {
    18. return new IHelloService() {
    19. @Override
    20. public String hello(String name) {
    21. log.error("调用qingfeng-server-system服务出错", throwable);
    22. return "调用出错";
    23. }
    24. };
    25. }
    26. }


    5、通过这个FeignClient调用即可。