SpringCloud 学习(7):第一个Feign

本文介绍 Feign 的基本用法,演示如何通过 Feign 编写 Web 服务客户端,实现 GET 和 POST 请求,并展示自定义请求拦截器的应用。

一、简介##

Feign是一个声明性的Web服务客户端。 它使编写Web服务客户端变得更容易。 
要使用Feign,请创建一个界面并对其进行注释。 它具有可插入的注释支持,
包括Feign注释和JAX-RS注释。 Feign还支持可插拔编码器和解码器。
简单的说Feign就是一个restful客户端。

二、Feign hello world

这篇文章主要通过写一个简单Feign程序,来了解一下Feign的原理。

这里写图片描述

项目非常简单,通过feign-service提供3个接口,通过feign-client 对接口进行访问。
废话不多说,直接上代码:


一、feign-service

  • pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.warrior</groupId>
    <artifactId>feign-service</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.46</version>
        </dependency>
    </dependencies>
</project>
  • Application.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author: lqh
 * @description:
 * @program: feign-service
 * @create: 2018-07-02 10:25
 **/
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

  • application.properties
server.port = 2001
  • Person.java
public class Person {
    private Integer id;
    private Integer age;
    private String name;

    public Integer getId() {
        return id;
    }

    public Person setId(Integer id) {
        this.id = id;
        return this;
    }

    public Integer getAge() {
        return age;
    }

    public Person setAge(Integer age) {
        this.age = age;
        return this;
    }

    public String getName() {
        return name;
    }

    public Person setName(String name) {
        this.name = name;
        return this;
    }
}

  • PersonController.java
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.*;
 
@RestController
public class PersonController {

    @RequestMapping("hello")
    public String hello(){
        return "hello world.";
    }

    @RequestMapping("getPerson")
    public String hello(@RequestParam("id") Integer id){
        Person person = new Person();
        person.setId(id);
        person.setAge(23);
        person.setName("warrior");
        return JSON.toJSONString(person);
    }

    @PostMapping("insertPerson")
    public String insertPerson(@RequestBody Person person){
        return person.getName();
    }
}


二、feign-client

  • pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.warrior</groupId>
    <artifactId>feign-client</artifactId>
    <version>1.0-SNAPSHOT</version>

    <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>
    </dependencies>
</project>
  • Person.java
public class Person {
    private Integer id;
    private Integer age;
    private String name;

    public Integer getId() {
        return id;
    }

    public Person setId(Integer id) {
        this.id = id;
        return this;
    }

    public Integer getAge() {
        return age;
    }

    public Person setAge(Integer age) {
        this.age = age;
        return this;
    }

    public String getName() {
        return name;
    }

    public Person setName(String name) {
        this.name = name;
        return this;
    }
}

  • FeignClient.java
 import feign.Headers;
import feign.Param;
import feign.RequestLine;

public interface FeignClient {
    @RequestLine("GET /hello") //指定请求方式 uri
    String hello();

    @RequestLine("GET /getPerson?id={id}") //有参数的格式
    Person getPerson(@Param("id") Integer id);

    @RequestLine("POST /insertPerson")
    @Headers("Content-Type: application/json") //指定参数为json格式
    public String insertPerson(Person person);
}
  • FeignTest.java

import com.google.gson.Gson;
import feign.Feign;
import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder;
 
public class FeignTest {
    public static void main(String[] args) {
        //1.无参
/*        FeignClient feignClient = Feign.builder()
                .target(FeignClient.class, "http://localhost:2001");
        String res = feignClient.hello();
        System.out.println("res:" + res);*/

        //2.使用解码器
/*        FeignClient feignClient = Feign.builder()
                .decoder(new GsonDecoder())
                .target(FeignClient.class, "http://localhost:2001");
        Person person = feignClient.getPerson(1);
        System.out.println("person:" + person.getName());*/

        //3.使用编码器
        FeignClient client = Feign.builder().encoder(new GsonEncoder())
                .target(FeignClient.class, "http://localhost:2001");
        Person person = new Person();
        person.setId(1);
        person.setAge(22);
        person.setName("warrior");
        String res = client.insertPerson(person);
        System.out.println(res);
    }
}


三、自定义请求拦截器 :
修改feign-client项目如下–>
这里写图片描述

  • Feign.java

import com.warrior.Person;
import feign.Headers;
import feign.Param;
import feign.RequestLine;

public interface FeignClient {
    @RequestLine("GET /hello") //指定请求方式 uri
    String hello();

    @RequestLine("GET /getPerson?id={id}") //有参数的格式
    Person getPerson(@Param("id") Integer id);

    @RequestLine("POST /insertPerson")
    public String insertPerson(Person person);
}

  • MyRequestIntercepter.java
import feign.RequestInterceptor;
import feign.RequestTemplate;

 
public class MyRequestIntercepter implements RequestInterceptor{
    public void apply(RequestTemplate requestTemplate) {
        System.out.println("自定义请求拦截器...............");
        requestTemplate.header("Content-type","application/json");
    }
}

  • RequestIntercepterMain.java
import com.warrior.Person;
import feign.Feign;
import feign.Logger;
import feign.gson.GsonEncoder;

  
public class RequestIntercepterMain {
    public static void main(String[] args) {
        FeignClient client = Feign.builder()
                .requestInterceptor(new MyRequestIntercepter())//设置拦截器
                .encoder(new GsonEncoder())
                .logLevel(Logger.Level.FULL) //设置日志级别
                .logger(new Logger.JavaLogger().appendToFile("logs/xx.log"))//设置日志文件
                .target(FeignClient.class, "http://localhost:2001");
        Person person = new Person();
        person.setId(1);
        person.setAge(22);
        person.setName("warrior");
        String res = client.insertPerson(person);
        System.out.println(res);
    }
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值