SpringCloud——声明式 Feign 知识篇

目录

Feign-0 Feign的官方简介

 

Feign-1.1 Feign的文档简介

Feign-1.2 Feign的小白实战GET

Feign-1.3 Feign的小白实战POST

Feign-1.4 Feign 会遇到的问题

 

Feign-2.1 覆写Feign的默认配置

 

Fegin-3.1 查看当前eureka有哪些服务

Fegin-3.2 论证Fegion支持SpringMVC注解

Fegin-3.3 Fegion支持SpringMVC注解总结

Fegin-3.4 Fegion支持SpringMVC注解遇到的问题

Fegin-3.5 Fegion的日志——DEBUG

Fegin-3.5 Fegion的日志——FULL

Fegion-End 解决Fegion第一次请求 timeout 的问题

Zuul基本知识

Hystrix基本知识

Sidecar


  • Feign-0 Feign的官方简介

Feign is a declarative web service client. It makes writing web service clients easier. To use Feign create an interface and annotate it. It has pluggable annotation support including Feign annotations and JAX-RS annotations. Feign also supports pluggable encoders and decoders. Spring Cloud adds support for Spring MVC annotations and for using the same HttpMessageConverters used by default in Spring Web. Spring Cloud integrates Ribbon and Eureka to provide a load balanced http client when using Feign.

Feign是声明式的HttpClient,如果想要使用在接口上添加注解,整合了ribbon和eureka,还可以是用SpringMVC的注解,降低我们的学习成本。

Feign的github地址:https://github.com/OpenFeign/feign

  • Feign-1.1 Feign的文档简介

  1. 文档地址:【ctrl+f Declarative】http://projects.spring.io/spring-cloud/spring-cloud.html#_service_discovery_eureka_clients
  • Feign-1.2 Feign的小白实战GET

  1. 1 添加Feign依赖
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
  1. 2 启动类加上注解@EnableFeignClients
@EnableEurekaClient
@EnableFeignClients
@SpringBootApplication
public class FeignApplication {

	public static void main(String[] args) {
		SpringApplication.run(FeignApplication.class, args);
	}

}
  1. 3 创建feignInterface.UserFeignClient.java接口在接口上添加注解
@FeignClient("provider-user")
public interface UserFeignClient {

    @RequestMapping(value = "/simple/{id}", method = RequestMethod.GET)
    public User findById(@PathVariable("id") Long id); // 两个坑:1. @GetMapping不支持   2. @PathVariable得设置value
}
  1. 4 创建 MovieController.java调用UserFeignClient.java,将之前的RestTemplate内容注销。
@RestController
public class MovieController {
    /*
    @Autowired
    private RestTemplate restTemplate;

    @Value("${user.userServicePath}")
    private String userServicePath;

    @GetMapping("/movie/{id}")
    public User findById(@PathVariable Long id) {
        return this.restTemplate.getForObject(this.userServicePath + id, User.class);
    }
    */
    @Autowired
    private UserFeignClient userFeignClient;

    @GetMapping("/movie/{id}")
    public User findById(@PathVariable Long id) {
        return this.userFeignClient.findById(id);
    }
}
  1. 5 结果如下

  1. 6 测试效果

点击feign-client:7901输入接口路径http://192.168.4.160:7901/movie/1

{
    "id": 1,
    "username": "user1",
    "name": "张三",
    "age": 20,
    "balance": 100
}
  • Feign-1.3 Feign的小白实战POST

  1. 1 在请求的服务中添加Post接口
@PostMapping("/user")
public User postUser(@RequestBody User user) {
    return user;
}
  1. 2 feignInterface.UserFeignClient.java接口在接口上添加内容
//只要参数是复杂对象,即使指定了是GET方法,feign依然会以POST方法进行发送请求
@RequestMapping(value = "/user", method = RequestMethod.POST)
public User postUser(@RequestBody User user);
  1. 3 创建 MovieController.java调用UserFeignClient.java,将之前的RestTemplate内容注销。
@PostMapping("/user")
public User postUser(@RequestBody User user) {
    return user;
}
  1. 4 PostMan测试http://192.168.4.160:7901/user结果
{
    "id": 1,
    "username": "user1",
    "name": "张三",
    "age": 20,
    "balance": 100
}
  1. 5 图示

 

  • Feign-1.4 Feign 会遇到的问题

  1. 会发现启动不起来情况1的解决办法【@GetMapping不支持】

@RequestMapping(value = "/movie/{id}", method = RequestMethod.GET)

  1. 会发现启动不起来情况1的解决办法【PathVariable annotation was empty on param 0.】

原来的@PathVariable id——> 变成 @PathVariable("id") id

  • Feign-2.1 覆写Feign的默认配置

  1. 文档地址:【ctrl+f Overriding】http://projects.spring.io/spring-cloud/spring-cloud.html#spring-cloud-feign-overriding-defaults
    @FeignClient(name = "stores", configuration = FooConfiguration.class)
    public interface StoreClient {
        //..
    }

    WARING:The FooConfiguration has to be @Configuration but take care that it is not in a @ComponentScanfor the main application context, otherwise it will be used for every @FeignClient. If you use @ComponentScan (or @SpringBootApplication) you need to take steps to avoid it being included (for instance put it in a separate, non-overlapping package, or specify the packages to scan explicitly in the @ComponentScan).

  2.  创建FeignConsumerApplication.java,添加@EnableFeignClients
    @EnableEurekaClient
    @EnableFeignClients
    @SpringBootApplication
    public class FeignConsumerApplication {
    
    	public static void main(String[] args) {
    		SpringApplication.run(FeignConsumerApplication.class, args);
    	}
    
    }

     

  3. 创建User.java
    public class User {
        private Long id;
    
        private String username;
    
        private String name;
    
        private Short age;
    
        private BigDecimal balance;
    
        public Long getId() {
            return this.id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public String getUsername() {
            return this.username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getName() {
            return this.name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Short getAge() {
            return this.age;
        }
    
        public void setAge(Short age) {
            this.age = age;
        }
    
        public BigDecimal getBalance() {
            return this.balance;
        }
    
        public void setBalance(BigDecimal balance) {
            this.balance = balance;
        }
    
    }

     

  4. 创建UserFeignClient.java使用name和configuration为ConfigFeignClient
    @FeignClient(name = "provider-user", configuration = ConfigFeignClient.class)
    public interface UserFeignClient {
        
        @RequestLine("GET /simple/{id}")
        public User findById(@Param("id") Long id);
        
    }
    
    @Configuration
    public class ConfigFeignClient {
        @Bean
        public Contract feignContractg() {
            return new feign.Contract.Default();
        }
    
    }

    此时启动时启动不成功的,解决办法参考文档:https://github.com/OpenFeign/feign#static-and-default-methods

  5.   创建MovieController.java
    @RestController
    public class MovieController {
    
        @Autowired
        private UserFeignClient userFeignClient;
    
        @GetMapping("/movie/{id}")
        public User findById(@PathVariable Long id) {
            return this.userFeignClient.findById(id);
        }
    
    }

     

  6.  GET http://192.168.1.2:7903/movie/1 
    {
        "id": 1,
        "username": "user1",
        "name": "张三",
        "age": 20,
        "balance": 100
    }

    success!!!


  • Fegin-3.1 查看当前eureka有哪些服务

  1. 查看所有服务的访问地址:http://localhost:8761/eureka/apps
    <applications>
        <versions__delta>1</versions__delta>
        <apps__hashcode>UP_1_</apps__hashcode>
        <application>
            <name>PROVIDER-USER</name>
            <instance>
                <instanceId>provider-user:7900</instanceId>
                <hostName>192.168.1.2</hostName>
                <app>PROVIDER-USER</app>
                <ipAddr>192.168.1.2</ipAddr>
                <status>UP</status>
                <overriddenstatus>UNKNOWN</overriddenstatus>
                <port enabled="true">7900</port>
                <securePort enabled="false">443</securePort>
                <countryId>1</countryId>
                <dataCenterInfo class="com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo">
                    <name>MyOwn</name>
                </dataCenterInfo>
                <leaseInfo>
                    <renewalIntervalInSecs>30</renewalIntervalInSecs>
                    <durationInSecs>90</durationInSecs>
                    <registrationTimestamp>1551703297605</registrationTimestamp>
                    <lastRenewalTimestamp>1551703717525</lastRenewalTimestamp>
                    <evictionTimestamp>0</evictionTimestamp>
                    <serviceUpTimestamp>1551703296947</serviceUpTimestamp>
                </leaseInfo>
                <metadata>
                    <management.port>7900</management.port>
                </metadata>
                <homePageUrl>http://192.168.1.2:7900/</homePageUrl>
                <statusPageUrl>http://192.168.1.2:7900/actuator/info</statusPageUrl>
                <healthCheckUrl>http://192.168.1.2:7900/actuator/health</healthCheckUrl>
                <vipAddress>provider-user</vipAddress>
                <secureVipAddress>provider-user</secureVipAddress>
                <isCoordinatingDiscoveryServer>false</isCoordinatingDiscoveryServer>
                <lastUpdatedTimestamp>1551703297605</lastUpdatedTimestamp>
                <lastDirtyTimestamp>1551703296607</lastDirtyTimestamp>
                <actionType>ADDED</actionType>
            </instance>
        </application>
    </applications>
  2. 查看特定服务的访问地址——上述的application name 为PROVIDER-USER例:http://localhost:8761/eureka/apps/PROVIDER-USER
  • Fegin-3.2 论证Fegion支持SpringMVC注解

  1. 1 新增FeignClient2.java,利用url,指定访问到eureka,name此时就无所谓了,但是还是需要填写,如“xxxx”
@FeignClient(name = "xxxx", url = "http://localhost:8761/,configuration = Configuration2.class")
public interface FeignClient2 {
    
    @RequestMapping(value = "/eureka/apps/{serviceName}")
    public String findServiceInfoFromEurekaByServiceName(@PathVariable("serviceName") String serviceName);

}
  1. 2 新增Configuration2.java
@Configuration
public class Configuration2 {
  @Bean
  public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
    return new BasicAuthRequestInterceptor("user", "123");
  }
}
  1. 3 新增MovieController.java内容

  1. 4 访问结果http://192.168.1.2:7903/PROVIDER-USER

  • Fegin-3.3 Fegion支持SpringMVC注解总结

结论:

    在UserFeignClient.java中我们使用@RequestLine,但没有使用url,在第二个使用了FeignClient2.java和@RequestMapping,后者是SpringMVC注解,发现也能访问成功,也就是说是支持的。

  • Fegin-3.4 Fegion支持SpringMVC注解遇到的问题

主要是和application.java同级别问题,不然会启动报错!!

  • Fegin-3.5 Fegion的日志——DEBUG

  1. 文档:http://projects.spring.io/spring-cloud/spring-cloud.html#_feign_logging
    logging.level.project.user.UserClient: DEBUG
  2. feign默认的日志级别是DEBUG,application.yml
    logging:
      level:
        com.example.demo.feignInterface.UserFeignClient: DEBUG # 将Feign接口的日志级别设置成DEBUG,因为Feign的Logger.Level只对DEBUG作出响应。
    
    # 注意上面层级问题 很容易写成level和项目名称同级别,就直接启动报错
    

     

  3. 访问 http://192.168.1.2:7903/movie/1 结果(什么都不打印)

  • Fegin-3.5 Fegion的日志——FULL

  1. 1 因为UserFeignClient.java对应的是ConfigFeignClient,直接在ConfigFeignClient修改添加!!!进行第三步:Logger Leavel

  1. 2 结果

  • Fegion-End 解决Fegion第一次请求 timeout 的问题

方法1:将默认的hystrix时间1s延长
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000

方法2:禁用hystrix的timeout enabled属性
hystrix.command.default.execution.timeout.enabled: false

方法3:直接禁用feign的hystrix(最彻底的方法)
feign:
  hystrix:
    enabled: false # 索性禁用feign的hystrix
  • Zuul基本知识

  1. link 上篇
  2. link 下篇
  • Hystrix基本知识

link

  • Sidecar

  1. ​​​​​​​link
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值