Feign

Feign是spring cloud中服务消费端的调用框架,通常与ribbon,hystrix等组合使用。

但是在某些项目中,由于遗留原因,整个系统并不是spring cloud项目,甚至不是spring项目,而使用者关注的重点仅仅是简化http调用代码的编写。

如果采用httpclient或者okhttp这样相对较重的框架,对初学者来说编码量与学习曲线都会是一个挑战,而使用spring中RestTemplate,又没有配置化的解决方案,由此想到是否可以脱离spring cloud,独立使用Feign。

maven依赖

<dependency>
    <groupId>com.netflix.feign</groupId>
    <artifactId>feign-core</artifactId>
    <version>8.18.0</version>
</dependency>

自定义接口

import feign.Param;
import feign.RequestLine;

public interface RemoteService {
    
    @RequestLine("GET /users/list?name={name}")
    String getOwner(@Param(value = "name") String name);
}

通过@RequestLine指定HTTP协议及URL地址

配置类

RemoteService service = Feign.builder()
            .options(new Options(1000, 3500))
            .retryer(new Retryer.Default(5000, 5000, 3))
            .target(RemoteService.class, "http://127.0.0.1:8085");

options方法指定连接超时时长及响应超时时长,retryer方法指定重试策略,target方法绑定接口与服务端地址。返回类型为绑定的接口类型。

调用

String result = service.getOwner("scott");

与调用本地方法相同的方式调用feign包装的接口,直接获取远程服务提供的返回值。

附:服务生产者
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value="users")
public class UserController {
    
    @RequestMapping(value="/list",method={RequestMethod.GET,RequestMethod.POST,RequestMethod.PUT})
    @ResponseBody
    public String list(@RequestParam String name) throws InterruptedException{
        return name.toUpperCase();
    }
}

更进一步

在项目中,服务消费端与生产端之间交换的数据往往是一或多个对象,feign同样提供基于json的对象转换工具,方便我们直接以对象形式交互。

业务接口

public interface RemoteService {
    
    @Headers({"Content-Type: application/json","Accept: application/json"})
    @RequestLine("POST /users/list")
    User getOwner(User user);
}

加入@Headers注解,指定Content-Type为json

配置

RemoteService service = Feign.builder()
                .encoder(new JacksonEncoder())
                .decoder(new JacksonDecoder())
                .options(new Options(1000, 3500))
                .retryer(new Retryer.Default(5000, 5000, 3))
                .target(RemoteService.class, "http://127.0.0.1:8085");

encoder指定对象编码方式,decoder指定对象解码方式。这里用的是基于Jackson的编、解码方式,需要在pom.xml中添加Jackson的依赖

<dependency>
    <groupId>com.netflix.feign</groupId>
    <artifactId>feign-jackson</artifactId>
    <version>8.18.0</version>
</dependency>

调用

User result = service.getOwner(u);
附:服务生产者
@Controller
@RequestMapping(value="users")
public class UserController {
    
    @RequestMapping(value="/list",method={RequestMethod.GET,RequestMethod.POST,RequestMethod.PUT})
    @ResponseBody
    public User list(@RequestBody User user) throws InterruptedException{
        System.out.println(user.getUsername());
        user.setId(100L);
        user.setUsername(user.getUsername().toUpperCase());
        return user;
    }
}

唯一的变化就是使用了@RequestBody来接收json格式的数据。



作者:SamHxm
链接:http://www.jianshu.com/p/3d597e9d2d67
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
### Feign技术介绍 Feign 以其声明式的使用方式和灵活的扩展能力,成为微服务架构中实现 HTTP 通信的利器。随着微服务架构的不断发展,Feign 在远程调用中的地位将更加重要[^1]。 Feign 的基本原理是通过接口和注解的方式来定义服务之间的调用,它会根据定义的接口和注解生成代理对象,这个代理对象会处理 HTTP 请求的发送和响应的接收。 ### Feign使用指南 #### 基本使用 定义一个 Feign 客户端接口,使用 `@FeignClient` 注解指定服务名。示例代码如下: ```java import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @FeignClient(name="systemClient") public interface SystemClient { @RequestMapping(path="/llsydn/importExcel", consumes={"multipart/form-data"}, method = RequestMethod.POST) JsonResult importExcel(@RequestPart(name="file") MultipartFile file); } ``` #### 超时时间设置 可以针对指定的 Feign client 进行超时时间设置,不过文档中未详细给出超时设置代码,通常可以在配置文件中设置,示例如下(不同版本可能有差异): ```yaml feign: client: config: systemClient: connectTimeout: 5000 readTimeout: 5000 ``` #### 日志级别设置 基于配置文件修改 Feign 的日志级别可以针对单个服务,示例如下: ```yaml feign: client: config: userservice: # 针对某个微服务的配置,此处是服务名称 loggerLevel: FULL # 日志级别 ``` ### Feign与SSO结合使用 在实际应用中,若要将 Feign 与 SSO 结合使用,通常需要在 Feign 的请求拦截器中添加 SSO 的认证信息。例如,在请求头中添加 SSO 的 token。示例代码如下: ```java import feign.RequestInterceptor; import feign.RequestTemplate; import org.springframework.stereotype.Component; @Component public class SSOFeignInterceptor implements RequestInterceptor { @Override public void apply(RequestTemplate template) { // 从某个地方获取 SSO 的 token,这里只是示例 String ssoToken = getSSOToken(); template.header("Authorization", "Bearer " + ssoToken); } private String getSSOToken() { // 实现获取 SSO token 的逻辑 return "your_sso_token"; } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值