1.OpenFeign
OpenFeign是一个声明式的http客户端,作用是基于SpringMVC的常见注解,实现更便捷的http请求发送
2.OpenFeign使用步骤
(1)导入依赖坐标
<!--OpenFeign--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency><!--LoadBalancer--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-loadbalancer</artifactId></dependency>
(2)启用OpenFeign功能
在SpringBoot启动类上加@EnableFeignClients注解,启用OpenFeign功能
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;@SpringBootApplication
@EnableFeignClients // 启用OpenFeign功能
public class UserServiceApplication {public static void main(String[] args) {SpringApplication.run(UserServiceApplication.class, args);}
}
(3)编写FeignClient接口
import com.example.domain.Order;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;@FeignClient("order-service") // 配置要调用的服务名称
public interface OrderClient {@GetMapping("/demos") // 配置要调用服务的请求路径Order getOrder();
}
(4)使用FeignClient接口,实现远程调用
import com.example.client.OrderClient;
import com.example.domain.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("demos")
public class DemoController {@Autowiredprivate OrderClient orderClient;@GetMappingpublic Order getOrder() {System.out.println("发生了远程调用");return orderClient.getOrder();}
}
3.修改OpenFeign底层连接池
(1)导入依赖坐标
<dependency><groupId>io.github.openfeign</groupId><artifactId>feign-okhttp</artifactId></dependency>
(2)在配置文件中开启连接池
# OpenFeign配置
feign:# okhttp连接池配置okhttp:enabled: true
4.OpenFeign日志等级
(1)日志等级
注:OpenFeign只会在FeignClient所在包的日志级别为DEBUG时,才会输出日志
等级 | 描述 |
---|---|
NONE | 不记录任何日志信息(默认值) |
BASIC | 仅记录请求的方法,URL及响应状态码和执行时间 |
HEADERS | 在BASIC的基础上,额外记录了请求和响应的头信息 |
FULL | 记录所有请求和响应的明细,包括头信息、请求体、元数据 |
(2)修改OpenFeign日志等级
定义日志等级:
public class OpenFeignConfig {@Beanpublic Logger.Level feignLoggerLevel() {return Logger.Level.FULL;}
}
另某一个FeignClient生效:
@FeignClient(value = "order-service",configuration = OpenFeignConfig.class)
全局配置,另所有FeignClient生效
@EnableFeignClients(defaultConfiguration = OpenFeignConfig.class)