Feign Java HTTP客户端开发的工具

Feign是简化Java HTTP客户端开发的工具(java-to-httpclient-binder),它的灵感来自于Retrofifit、JAXRS-2.0和
WebSocket。Feign的初衷是降低统一绑定Denominator到HTTP API的复杂度,不区分是否为restful
比如有一个maven 项目下有三个服务模块 Eureka服务模块 、test 、company
test  调用 company 模块的接口

1.test模块添加依赖

<dependency>        
 <groupId>org.springframework.cloud</groupId>            
 <artifactId>spring-cloud-starter-openfeign</artifactId>            
</dependency>
View Code

2.test 启动类添加注解

@EnableDiscoveryClient
@EnableFeignClients

3.在test 服务模块下创建调用comapny API的接口

package com.zhao.system.feign.client;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * 声明接口 feign 调用其他微服务
 */
@FeignClient("company") //company 这是你要调用的那个服务的名称
public interface feign {
    /**
     * 调用微服务的接口
     */
    //feigin
    @GetMapping("/feign/{name}")
    public String feign(@PathVariable("name") String name);

}
View Code

4.修改test 下的controller

  @Autowired
    private feign feign;
    /**
     * 测试Feign
     */
    @GetMapping("/testFeign/{name}")
    public  String testFeign(@PathVariable(value = "name") String name){

       return feign.feign(name);
    }
View Code

要调用company 模块下的接口代码

   //feigin
    @GetMapping("/feign/{name}")
    public String feign(@PathVariable("name") String name)  {
      return  "Feign是简化Java HTTP客户端开发的工具 "+name;
    }
View Code

依赖

<!--        eureka  客户端依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

注意: 微服务下test模块登陆了,要想调用company 模块时携带请求头 (我写的登录验证信息放在了请求头里)要配置

@Configuration
public class FeignConfiguration {
    //配置feign拦截器,解决请求头问题
    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {

            //获取所有浏览器发送的请求属性,请求头赋值到feign
            public void apply(RequestTemplate requestTemplate) {
                //请求属性
                ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
                if(attributes != null) {
                    HttpServletRequest request = attributes.getRequest();
                    //获取浏览器发起的请求头
                    Enumeration<String> headerNames = request.getHeaderNames();
                    if (headerNames != null) {
                        while (headerNames.hasMoreElements()) {
                            String name = headerNames.nextElement(); //请求头名称 Authorization
                            String value = request.getHeader(name);//请求头数据 "Bearer b1dbb4cf-7de6-41e5-99e2-0e8b7e8fe6ee"
                            requestTemplate.header(name,value);
                        }
                    }
                }

            }
        };
    }
}
View Code

 

posted @ 2020-01-29 21:27  Angry-rookie  阅读(201)  评论(0)    收藏  举报