• Feign 客户端的使用 二


    一、Feign的使用(客户端调用 json/xml格式的接口)

    1.服务端接口编写

    <parent>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-parent</artifactId>
          <version>2.0.2.RELEASE</version>
      </parent>
    
      <dependencies>
          <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-web</artifactId>
          </dependency>
    
        <dependency>
          <groupId>com.fasterxml.jackson.jaxrs</groupId>
          <artifactId>jackson-jaxrs-xml-provider</artifactId>
          <version>2.9.0</version>
        </dependency>
      </dependencies>
      @RequestMapping(value = "/hello", method = RequestMethod.GET)
        public String hello() {
            return "hello world";
        }
    
        @RequestMapping(value = "/person/create", method = RequestMethod.POST,
                produces = MediaType.APPLICATION_JSON_VALUE,
                consumes = MediaType.APPLICATION_JSON_VALUE)
        public String createPerson(@RequestBody Person person) {
            System.out.println(person.getName() + "~~~~~~~" +person.getAge());
            return "success, id:" + person.getId();
        }
    
        @RequestMapping(value = "/createXmlPerson/create", method = RequestMethod.POST,
                produces = MediaType.APPLICATION_XML_VALUE,
                consumes = MediaType.APPLICATION_XML_VALUE)
        public String createXmlPerson(@RequestBody Person person) {
            System.out.println(person.getName() + "~~~~~~~" +person.getAge());
            return "<result><message>success</message></result>";
        }

    2.客户端编写

    (1)导入jar包

    <dependencies>
        <dependency>
          <groupId>io.github.openfeign</groupId>
          <artifactId>feign-core</artifactId>
          <version>9.5.0</version>
        </dependency>
    
        <dependency>
          <groupId>io.github.openfeign</groupId>
          <artifactId>feign-gson</artifactId>
          <version>9.5.0</version>
        </dependency>
    
        <!--配置xml客户端-->
        <dependency>
          <groupId>io.github.openfeign</groupId>
          <artifactId>feign-jaxb</artifactId>
          <version>9.5.0</version>
        </dependency>
    
        <dependency>
          <groupId>org.projectlombok</groupId>
          <artifactId>lombok</artifactId>
          <version>1.16.20</version>
        </dependency>
    
        <dependency>
          <groupId>javax.xml.bind</groupId>
          <artifactId>jaxb-api</artifactId>
          <version>2.3.0</version>
        </dependency>
    
        <!--httpclient-->
        <dependency>
          <groupId>org.apache.httpcomponents</groupId>
          <artifactId>httpclient</artifactId>
          <version>4.5.5</version>
        </dependency>
      </dependencies>

    (2)编写客户端测试代码

    public interface ClientInterface {
    
        @RequestLine("GET /hello")
        public String hello();
    
        @RequestLine("GET /person/{id}")
        public Person getPerson(@Param("id") Integer id);
    
        @RequestLine("POST /person/create")
        @Headers("Content-Type: application/json")
        public String createPerson(Person person);
    
        @RequestLine("POST /createXmlPerson/create")
        @Headers("Content-Type: application/xml")
        public Result createXmlPerson(Person person);
    }
    public static void main(String[] args) {
            //hello
            ClientInterface helloClient = Feign.builder().target(ClientInterface.class, "http://localhost:8080");
    
            String hello = helloClient.hello();
            System.out.println(hello);
    
            //json 创建 Person
            ClientInterface creatPersonInter = Feign.builder()
                    .encoder(new GsonEncoder())
                    .target(ClientInterface.class, "http://localhost:8080");
    
            Person person = new Person();
            person.setAge(18);
            person.setId(1);
            person.setName("admin");
    
            String result = creatPersonInter.createPerson(person);
            System.out.println("result:" + result);
    
            //xml 创建 Person
            JAXBContextFactory jaxbContextFactory = new JAXBContextFactory.Builder().build();
            ClientInterface xmlClient = Feign.builder().encoder(new JAXBEncoder(jaxbContextFactory))
                    .decoder(new JAXBDecoder(jaxbContextFactory))
                    .target(ClientInterface.class, "http://localhost:8080/");
    
            Person person1 = new Person();
            person1.setAge(18);
            person1.setId(1);
            person1.setName("admin");
            Result result2 = xmlClient.createXmlPerson(person1);
            System.out.println("result:"+result2.getMessage());
        }

    二、自定义Feign客户端

    1.编写myClient

    import feign.Client;
    import feign.Request;
    import feign.Response;
    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 java.io.IOException;
    import java.net.URI;
    import java.net.URISyntaxException;
    import java.util.Collection;
    import java.util.HashMap;
    
    public class MyClient implements Client {
        @Override
        public Response execute(Request request, Request.Options options) throws IOException {
            try {
                System.out.println("自定义的client");
    
                //创建一个默认的客户端
                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 d的响应对象转换为Feign的Response
                Response response = Response.builder()
                        .body(body)
                        .headers(new HashMap<String, Collection<String>>())
                        .status(httpResponse.getStatusLine().getStatusCode())
                        .build();
                return response;
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    2.编写MyClientTest测试

    public static void main(String[] args) {
            ClientInterface clientInterface = Feign.builder()
                    .client(new MyClient())
                    .target(ClientInterface.class, "http://localhost:8080");
    
            String hello = clientInterface.hello();
            System.out.println(hello);
        }
  • 相关阅读:
    jekyll+github搭建个人博客总结
    ES6-let命令
    Ajax-快速上手前后端交互
    第一次项目总结——校园博览会
    Python获取exe文件版本
    @JsonFormat与@DateTimeFormat注解的使用
    前后端时间转化
    左右flex布局
    fastjson将json字符串转化成map的五种方法
    RestTemplate 发送post请求
  • 原文地址:https://www.cnblogs.com/gyli20170901/p/10082051.html
Copyright © 2020-2023  润新知