springcloud 之openfeign 远程调用

导入依赖

   //feign
 compileOnly 'org.springframework.cloud:spring-cloud-starter-openfeign:2.2.5.RELEASE'

spring boot 版本

plugins {
    id 'org.springframework.boot' version '2.2.10.RELEASE'
    id 'io.spring.dependency-management' version '1.0.10.RELEASE'
    id 'java'
}

注意点:springboot 和 springcloud 如果版本不兼容,自行寻找兼容版本

编写接口

@Service
@FeignClient(contextId = Constant.ServiceContextId,name = Constant.ServiceName,url = Constant.ServiceUrl,fallback = xxxRemoteServiceHystrix.class)
public interface xxxRemoteService {


    /**
     * 获取token
     * @param corpId  xxID
     * @param corpSecret xxx凭证密钥
     * @return JSONObject
     */
    @PostMapping(value = "/gettoken",consumes = MediaType.APPLICATION_JSON_VALUE)
    JSONObject getToken(@RequestParam("corpid") String corpId,@RequestParam("corpsecret")String corpSecret);

注意点:

  • contextId 服务id

  • name 服务名称(如果是同一个注册中心,就是服务名,如果是调用第三方接口可以自定义名称)

  • url 服务url(一般是IP加端口,如果是同一个注册中心,可不不填写该参数)

  • fallback 服务调用失败的处理类(熔断)

  • MediaType.APPLICATION_JSON_VALUE 请求的参数格式

  • @RequestParam("corpid") 必须指定参数名称否则调用失败

异常处理类

@Component
@Log4j2
public class xxxRemoteServiceHystrix implements xxxRemoteService {


    @Override
    public JSONObject getToken(String corpId, String corpSecret) {
        log.error(Constant.TokenError+"corpId:{}, corpSecret:{}",corpId,corpSecret);
        return new JSONObject().put("msg",Constant.TokenError);
    }

启动类

@SpringCloudApplication
@EnableFeignClients(basePackages = {"com.xxx.*.*.api.remote"})
@ComponentScan(com.xxx.*.*.api.remote.hystrix)
public class xxxSveApplication {
    public static void main(String[] args) {
        SpringApplication.run(xxxSveApplication.class, args);
    }

}

注意点:

如果调用的程序包在本项目直接使用注解 @EnableFeignClients 第三方包的话需要传入包路径@EnableFeignClients(basePackages = {"com.xxx...api.remote"}),并且需要加上 @ComponentScan(com.xxx...api.remote.hystrix)注解来将异常处理类注入bean 工厂中

结束语

  • spring.factories的用法

程序开发中,可能包名不一样,项目依赖的很多的jar 这样bean的注入就很麻烦,在resources下面创建文件夹META-INF 在创建一个文件spring.factories就很好解决该问题。

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
    com.xxx.xxx.xxx.api.remote.hystrix.xxxRemoteServiceHystrix
end

评论