調用外部接口方法之一 —— Feign 聲明式調用
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
- 亦可對比Springboot、feign更新時間,找到對應版本
spring-cloud-starter-openfeign
spring-boot-starter-parent
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);
}
}

浙公網安備 33010602011771號