首页 > 其他分享 >调用外部接口方法之一 —— Feign 声明式调用

调用外部接口方法之一 —— Feign 声明式调用

时间:2023-05-14 22:25:27浏览次数:27  
标签:Feign 调用 接口 newsfeed sinby springframework org import com

1、需求

  • 调用处理中心提供的接口,将数据处理同步到其他系统中。

2、实现

2.1、添加相关依赖

<!-- Feign -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
    <version>2.1.1.RELEASE</version>
</dependency>

此处,遇到Feign版本与SpringBoot版本冲突问题,最终用的Feign是2.1.1.RELEASE,而Springboot版本用的是2.2.6.RELEASE

2.2、添加相关配置

  • application.yml中添加
feignapi:
  # 处理中心地址
  url: https://********/api/

# 日志等级。将日志等级设置为debug,其主要目的是为了方便调试Feign。
logging:
  level:
    # 全局日志等级
    root: debug
    # feign日志等级
    com.foreign.feign.QueryClient: debug

  • 添加feign配置文件
package com.sinby.newsfeed.config;

import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FeignConfig {

    @Bean
    Logger.Level feignLoggerLevel() {
        // 设置日志等级
        return Logger.Level.FULL;
    }
}

在可以在此类中添加其他配置,如请求头Header(需重写RequestInterceptor的apply方法)

2.3、开启Feign客户端

  • 在启动类上添加@EnableFeignClients
package com.sinby.newsfeed;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

@EnableFeignClients
@SpringBootApplication
public class NewsFeedApplication {

    public static void main(String[] args) {
        SpringApplication.run(NewsFeedApplication.class, args);
    }

}

2.4、构建外部服务

  • 根据外部接口提供方提供的地址、接口名等等信息创建
package com.sinby.newsfeed.service;

import com.sinby.newsfeed.config.FeignConfig;
import com.sinby.newsfeed.entity.osys.HttpData;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;

@Component
@FeignClient(url = "${feignapi.url}", name = "otherSys", configuration = FeignConfig.class)
public interface HandleCenterFeign {

    @PostMapping("/hello")
    String hello(HttpData httpData);
}


2.5、使用

  • 如果上述配置都加了,过程中遇到的问题也解决了,用时候特别方便,声明调用就行!
package com.sinby.newsfeed.service.impl;

import com.sinby.newsfeed.entity.osys.HttpData;
import com.sinby.newsfeed.service.HandleCenterFeign;
import com.sinby.newsfeed.service.MsgHandleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class ExampleServiceImpl implements ExampleService {

    @Resource
    private HandleCenterFeign handleCenterFeign;

    @Resource
    private HttpData httpData;

    @Override
    public String sendMessage() {
        return handleCenterFeign.sendMessage(httpData);
    }
}

标签:Feign,调用,接口,newsfeed,sinby,springframework,org,import,com
From: https://www.cnblogs.com/azure-rain/p/17400390.html

相关文章