Feign用于一个微服务子系统调用另一个微服务子系统的接口,本质就是http请求。但是我们的微服务都是受保护的,没有合法的令牌是无法获取到数据的,并且Fein默认并不会帮我们传递令牌。
综于上述原因,这里有必要提及下当前系统中Feign的使用方式。
假如现在需要在qingfeng-server-hello系统中调用qingfeng-server-system系统中的TestController中的/hello接口数据,我们需要在qingfeng-server-hello系统中进行如下操作:
1、系统入口类上添加@EnableFeignClients注解;
咱们的系统需要增加:@EnableCloudApplication 因为在【@EnableCloudApplication】中包含了@EnableFeignClients的注解。
2、系统配置文件中添加如下配置:
feign:
hystrix:
enabled: true
hystrix:
shareSecurityContext: true
3、编写IHelloService:
@FeignClient(value = ServerConstant.QINGFENG_SERVER_SYSTEM, contextId = “helloServiceClient”, fallbackFactory = HelloServiceFallback.class)
package com.qingfeng.service;
import com.qingfeng.entity.ServerConstant;
import com.qingfeng.service.fallback.HelloServiceFallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* @author Administrator
* @version 1.0.0
* @ProjectName qingfeng-cloud
* @Description TODO
* @createTime 2021年04月19日 14:44:00
*/
@FeignClient(value = ServerConstant.QINGFENG_SERVER_SYSTEM, contextId = "helloServiceClient", fallbackFactory = HelloServiceFallback.class)
public interface IHelloService {
@GetMapping("hello")
public String hello(@RequestParam("name") String name);
}
4、编写HelloServiceFallback
package com.qingfeng.service.fallback;
import com.qingfeng.service.IHelloService;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* @ProjectName HelloServiceFallback
* @author Administrator
* @version 1.0.0
* @Description TODO
* @createTime 2021/4/19 0019 14:45
*/
@Slf4j
@Component
public class HelloServiceFallback implements FallbackFactory<IHelloService> {
@Override
public IHelloService create(final Throwable throwable) {
return new IHelloService() {
@Override
public String hello(String name) {
log.error("调用qingfeng-server-system服务出错", throwable);
return "调用出错";
}
};
}
}
5、通过这个FeignClient调用即可。