Spring Cloud_12_自定义Feign客户端

自定义Feign客户端

  • Feign使用一个Client接口发送请求,默认情况下,使用HttpURLConnection连接HTTP服务
  • 当然我们也可以实现自己的Feign客户端

1、构建服务器端

1.1、创建一个简单的服务端请求

package com.atm.cloud;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {

    @GetMapping("/hello")
    @ResponseBody
    public String hello() {
        return "Hello world!";
    }
}

2、构建客户端

2.1、引入httpclient依赖

<dependency>
    <groupId>org.apache.httpcomponentsgroupId>
    <artifactId>httpclientartifactId>
    <version>4.5.2version>
dependency>

2.2、编写自定义客户端

package com.atm.cloud;

import java.io.IOException;
import java.net.URI;
import java.util.Collection;
import java.util.HashMap;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import feign.Client;
import feign.Request;
import feign.Request.Options;
import feign.Response;

/**
 * feign.Client接口的实现类
 * 
 * @author AiTeMi
 *
 */
public class MyFeignClient implements Client {

    /**
     * 客户端实现过程:
     * 
     * 1.   在实现execute方法时,将Feign的Request实例,
     *      转化为HttpClient的HttpRequestBase,
     * 
     * 2.   再使用CloseableHttpClient来执行请求
     * 
     * 3.   得到响应HttpResponse实例后,
     *      再转换为Feign的Response实例返回
     */
    public Response execute(Request request, Options options)
            throws IOException {

        System.out.println("   --->>> 这是自定义的Feign客户端   <<<---   ");

        try {
            // 创建一个默认的客户端
            CloseableHttpClient httpClient = HttpClients.createDefault();

            // 获取调用的HTTP方法
            final String method = request.method();

            // 创建一个HttpClient的HttpRequest
            HttpRequestBase httpRequestBase = new HttpRequestBase() {
                @Override
                public String getMethod() {
                    return method;
                }
            };

            // 设置请求地址
            httpRequestBase.setURI(new URI(request.url()));

            // 执行请求,获取响应
            HttpResponse httpResponse = httpClient.execute(httpRequestBase);

            // 获取响应的主体内容
            byte[] body = EntityUtils.toByteArray(httpResponse.getEntity());

            // 将HttpClient的响应对象转化为Feign的Response
            Response response = Response.builder().body(body)
                    .headers(new HashMap>())
                    .status(httpResponse.getStatusLine().getStatusCode())
                    .build();

            return response;

        } catch (Exception e) {
            throw new IOException(e);
        }

    }

}

2.3、测试执行

package com.atm.cloud;

import feign.Feign;
import feign.gson.GsonEncoder;

public class FeignClientMain {

    public static void main(String[] args) {

        // 获取服务接口
        HelloClient helloClient = Feign.builder().encoder(new GsonEncoder())
                .client(new MyFeignClient())
                .target(HelloClient.class, "http://localhost:8080");

        // 请求Hello world接口
        String result = helloClient.sayHello();

        System.out.println("接口响应内容:" + result);
    }
}

  • 自定义客户端中并没有实现转换请求头等信息,因此本案例,无法请求其它格式的服务

你可能感兴趣的:(SpringCloud,SpringCloud)