zoukankan      html  css  js  c++  java
  • Feign引入使用

    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();
        }
  • 相关阅读:
    SIFT,SURF,ORB,FAST,BRISK 特征提取算法比较
    OpenCV 4.2.0 编译成功日志(Mac)
    Ceres Solver Bibliography
    Linux下重启就需要重新激活eth0的解决办法(ifup eth0)
    PS(光影魔术手)
    软件项目开发各阶段文档模板(参考)
    敏捷、瀑布开发模式
    QA
    QC
    会计人必知的实务基础知识
  • 原文地址:https://www.cnblogs.com/Payne-SeediqBale/p/15167387.html
Copyright © 2011-2022 走看看