3 Feign
3.1 思维导图
3.2 java都用什么调用接口
- httpclient:apache下的支持http协议的客户端工具包
- okhttp:安卓端比较火的轻量级框架,性能比较高,支持多种协议
- httpurlconnection: httpurlconnection 是标准的java类,可以发送Get,Post请求
- resttempplate:spring提供的访问rest服务的客户端,可以提高客户端编写效率
3.3 为什么要使用Feign,它有什么优势
- 声明式客户端,rest调用更简单
- 完全代理http请求,像调用方法一样使用它
- Feign可以与Eureka和Ribbon组合使用
3.4 spring cloud如何集成Feign
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
3.5 Feign怎么调用
1)Feign调用图
2)使用方法
第一步:定义Feign的客户端
package com.example.feigndemo.remote;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(value = "eureka-client-user-service")
public interface UserRemoteClient {
@GetMapping("/user/hello")
public String hello();
}
第二步:利用Feign来调用
package com.example.feigndemo.controller;
import com.example.feigndemo.remote.UserRemoteClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoController {
@Autowired
UserRemoteClient userRemoteClient;
@GetMapping("/callHello")
public String callHello() {
// 调用方式比restTemplate更加简单了
String result = userRemoteClient.hello();
System.out.println(" 调用结果:" + result);
return result;
}
}
3.6 Feign相关配置
1)日志配置
通过配置Feign日志,可以打印请求信息
配置类
package com.example.feigndemo.config;
import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeignConfiguration {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}
application.properties配置
logging.level.com.example.feigndemo.remote.UserRemoteClient=DEBUG
调试结果
2)认证配置
调用的接口存在权限控制,feign是怎么做的
- 使用Feign自带的basic认证
// Feign Basic认证配置
@Bean
public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
return new BasicAuthRequestInterceptor("user", "password");
}
- 自定义拦截器来实现认证
// Feign 自定义认证配置
@Bean
public FeignBasicAuthRequestInterceptor feignBasicAuthRequestInterceptor() {
return new FeignBasicAuthRequestInterceptor();
}
package com.example.feigndemo.auth;
import feign.RequestInterceptor;
import feign.RequestTemplate;
// 需要实现RequestInterceptor接口
public class FeignBasicAuthRequestInterceptor implements RequestInterceptor {
public FeignBasicAuthRequestInterceptor() {
}
@Override
public void apply(RequestTemplate requestTemplate) {
System.out.println("进入拦截器了");
}
}
- 调用结果
3)超时时间配置
@Bean
public Request.Options options() {
return new Request.Options(5000, 10000);
}
4)客户端组件配置
依赖引入
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
application.properties 配置
feign.httpclient.enabled=false
feign.okhttp.enabled=true
本文暂时没有评论,来添加一个吧(●'◡'●)