Feign的引入使用,代替自己使用http的請求。以下提供流程, 過程中參數需要自行替換,自學網址: https://github.com/mbrukman/netflix-feign/blob/master/README.md
1. 引入Maven
<properties>
<feign.version>8.18.0</feign.version>
</properties>
<!--feign--> <dependency> <groupId>com.netflix.feign</groupId> <artifactId>feign-jackson</artifactId> <version>${feign.version}</version> </dependency> <dependency> <groupId>com.netflix.feign</groupId> <artifactId>feign-core</artifactId> <version>${feign.version}</version> </dependency> <dependency> <groupId>com.netflix.feign</groupId> <artifactId>feign-httpclient</artifactId> <version>${feign.version}</version> </dependency>
2. 初始化Feign接口的配置
@Configuration public class FeignConfig { @Bean(value = "urlFeign") public UrlFeign getUrlFeign(){ return Feign.builder() //.logger(new Slf4jLogger()) // 此處為日志內容 //.logLevel(Logger.Level.FULL) .encoder(new JacksonEncoder()) // 參數編碼 .decoder(new JacksonDecoder()) // 返回結果解碼 .options(new Request.Options(10000,10000)) .target(UrlFeign.class, "https://api.sandbox.ebay.com");
}
}
3. 書寫Feign的請求接口, 也就是http請求實際地址和參數,GET請求,可以在url后加上對應參數
/** * @Description: eBay獲取相關數據接口https請求 * @author wxy * @Date 2021/8/18 10:19 **/ public interface UrlFeign { // 獲取庫存數據 @Headers({"X-EBAY-C-MARKETPLACE-ID: {marketplaceId}", "Accept: application/json", "Authorization: Bearer {accessToken}"}) @RequestLine("GET /sell/inventory/v1/inventory_item?limit={limit}&offset={offset}") InventoryRespVo getInventoryItems(@Param("marketplaceId") String marketplaceId, @Param("accessToken") String accessToken, @Param("limit") Integer limit, @Param("offset") Integer offset); }
4. 測試接口, 不過上面是ebay的接口,需要授權碼,可以去掉對應授權碼,自行測試對應地址
// 獲取庫存 @Test public void getInventoryItems() throws EBayException, IOException { InventoryRespVo getTransactions = eBayUrlFeign.getInventoryItems(MarketplaceEnum.EBAY_US.getId(), getTokenByRefreshToken(), 100,0); logger.info(JSONObject.toJSONString(getTransactions)); }
總結: 以上就是Feign的實際應用流程,此版本不與spring結合,可單獨移用。 POST請求,自行探索。
======================== 增加日志打印========================
1. 你有引入 slf4j 的依賴
2. 增加轉化配置類:
/** * Copyright 2012-2020 The Feign Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import feign.Request; import feign.Response; /** * Logs to SLF4J at the debug level, if the underlying logger has debug logging enabled. The * underlying logger can be specified at construction-time, defaulting to the logger for * {@link feign.Logger}. */ public class Slf4jLogger extends feign.Logger { private final Logger logger; public Slf4jLogger() { this(feign.Logger.class); } public Slf4jLogger(Class<?> clazz) { this(LoggerFactory.getLogger(clazz)); } public Slf4jLogger(String name) { this(LoggerFactory.getLogger(name)); } Slf4jLogger(Logger logger) { this.logger = logger; } @Override protected void logRequest(String configKey, Level logLevel, Request request) { if (logger.isDebugEnabled()) { super.logRequest(configKey, logLevel, request); } } @Override protected Response logAndRebufferResponse(String configKey, Level logLevel, Response response, long elapsedTime) throws IOException { if (logger.isDebugEnabled()) { return super.logAndRebufferResponse(configKey, logLevel, response, elapsedTime); } return response; } @Override protected void log(String configKey, String format, Object... args) { // Not using SLF4J's support for parameterized messages (even though it would be more efficient) // because it would // require the incoming message formats to be SLF4J-specific. if (logger.isDebugEnabled()) { logger.debug(String.format(methodTag(configKey) + format, args)); } } }
3. 在 FeignConfig 的配置中加上配置
@Configuration public class FeignConfig { @Bean(value = "urlFeign") public UrlFeign getUrlFeign(){ return Feign.builder() .logger(new Slf4jLogger()) // 此處為日志內容 .logLevel(Logger.Level.FULL) .encoder(new JacksonEncoder()) // 參數編碼 .decoder(new JacksonDecoder()) // 返回結果解碼 .options(new Request.Options(10000,10000)) .target(UrlFeign.class, "https://api.sandbox.ebay.com"); } }
4. 測試即可
======================== 針對直接對url下載請求,不做參數傳入的方式========================
1. 引入
2. 准備好url
3. 新建一個Feign的方法
public interface WishZFeign { @RequestLine("GET") Response loadToken(); }
4. new新的Feign對象,調用保存數據
@Test public void orderDownLoadTest() throws Exception { String url = "https://sweeper-sandbox-merchant-export.s3-us-west-1.amazonaws.com/5c174ef79203fd4e0d16e4fa-61259c55fc3137452295106d-2021-08-25-01%3A26%3A45.csv?Signature=MoOwHVE00GIMw2e%2BjSgLrUsZ8hY%3D&Expires=1630114070&AWSAccessKeyId=ASIA53ILURM7UCW2YT7X&x-amz-security-token=FwoGZXIvYXdzEBMaDKDyt6XTeyyUoGVbJCL1A20vpFI9UGRNhdT8MR8dX1meJkomRaSo0hPoOBZwYE4XS%2B8XelICYgOPb5Qv81B8ptCVgFjjFiwO%2BlfuU9kLBhmqkfJP3WL1AWG63gpJf/eBKRHgf8NPJ5z5Fwuous5nZuzy8DOMBeM382EU8L4GvfVvBTO9TKh8bLdR%2BFtLaF0KvMowBvMCPkioOlTdIOqSpflp3ukwIi4Owi%2BA6h9FTsxN7PNcq4JmMTiVepgwqYexQZW27EJrh4GEuHzyI5QVeHKRraUIJG53RB4JEHtBZvYpCRcKWMJgjmZboajcVz4lKUlEVJ9J2QsloCL6b9kBbBdMtOk98SRaeDUtYJ/Zz9wHq8xkArkL40AubD29sQr6qLDhk3ZSPfG9QgrHoR7b2x6HPJgH/oTM4NP/Kc85JYHwU%2Ba378BkSHHo0MOw0EEYEiJYgu2GK9CnvoBVWZQkpbU2KX6b1uWuxhfAq2HZqG8TmHwkVt9lsvFpW%2BYFcutzGjDcHzdKejL/n1EYt/dgNqX%2BsRQAsWjR6YgMkB6txnu9SvJg7ZJ5SRPKNvbk73KIFdCuGEB7E1WTO8DuRdzLCpfq8ZPdg3EDUthH44kmC786e7s66mO2oMYsV9JcSfvUFBa9ZPGlcKLqjF8ddrAfTrhHxNvDWlqUASXBE6KvoV5JW90iOSiWuZaJBjImOqxJESv6%2BA4NbqgFMC6TQMftUmpuuegfuQNy45eL9pjsfgw9FJA%3D"; WishZFeign target = Feign.builder().target(WishZFeign.class, url); Response down = target.loadToken(); byte[] b; try (InputStream inputStream = down.body().asInputStream()) { b = toByteArray(inputStream); } writeToLocal("D:\\company\\work\\wish\\導出_" + System.currentTimeMillis() + ".csv", b); } /** * InputStream 轉換成byte[] * * @param input * @return * @throws IOException */ private static byte[] toByteArray(InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[1024 * 4]; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); } return output.toByteArray(); } /** * 將bytes寫入本地文件(測試代碼) * * @param destination * @param bytes * @throws IOException */ private static void writeToLocal(String destination, byte[] bytes) throws IOException { FileOutputStream downloadFile = new FileOutputStream(destination); downloadFile.write(bytes); downloadFile.flush(); downloadFile.close(); }