首先看的是项目结构:
如图feign-serve模块就是我抽取的Feign
Spring.factories文件是SpringBoot在启动时进行自动装配:
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.itheima.feign.config.FeignAutoConfiguration
FeignAutoConfiguration类的内容:
@Configuration
@EnableFeignClients(basePackages = "com.xxx.feign")
public class FeignAutoConfiguration {
}
feign接口定义举例:
TeachingApiAgent接口内容:
import com.xuecheng.api.company.CompanyDTO;
import com.xuecheng.common.constant.XcFeignServiceNameList;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
* Feign远程调用 教学机构管理
*/
@FeignClient(value = XcFeignServiceNameList.XC_TEACHING_SERVICE)
public interface TeachingApiAgent {
String SERVICE_CONTEXT_PRE = "/teaching";
/**
* 根据租户Id获取机构信息(机构时一种租户)
* @param tenantId
* @return
*/
@GetMapping(SERVICE_CONTEXT_PRE + "/l/company/{tenantId}")
CompanyDTO getCompInfoDetail(@PathVariable(value = "tenantId") Long tenantId);
}
sentinel熔断降级选择FallbackFactory模式
TeachingApiAgentFallbackFactory类内容
package com.itheima.feign.agent;
import com.itheima.feign.agent.TeachingApiAgent;
import com.xuecheng.api.company.CompanyDTO;
import com.xuecheng.common.domain.code.CommonErrorCode;
import com.xuecheng.common.domain.response.RestResponse;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class TeachingApiAgentFallbackFactory implements FallbackFactory<TeachingApiAgent> {
@Override
public TeachingApiAgent create(Throwable throwable) {
return new TeachingApiAgent() {
@Override
public CompanyDTO getCompInfoDetail(Long tenantId) {
log.error("Feign 接口调用熔断降级,错误信息:{}", throwable.getMessage());
return null;
}
};
}
}
做完上述工程,就在远程调用方导入该模块的依赖
<dependency>
<groupId>com.xuecheng</groupId>
<artifactId>feign-server</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
并且再启动类上:
进行扫描feign接口所在的包
如此就可以远程调用了