示例代码
【pom.xml】
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>2.3.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.2.9.RELEASE</version>
</dependency>
【application.properties】
server.port=8080
spring.application.name=myFeignClient
management.server.port=7001
management.endpoints.web.exposure.include=*
logging.level.root=info
logging.level.com.chz.myFeignClient=DEBUG
【FeignConfiguration.java】
package com.chz.myFeignClient.config;
@Configuration
public class FeignConfiguration {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}
【TestController.java】
package com.chz.myFeignClient.controller;
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private TestBaiduFeignClient testBaiduFeignClient;
@GetMapping("/test")
public String test() {
return testBaiduFeignClient.testGet();
}
}
【TestBaiduFeignClient.java】
package com.chz.myFeignClient.feign;
@FeignClient(
name = "testBaiduFeignClient",
contextId = "com.chz.myFeignClient.feign.TestFeignClient",
url = "http://www.baidu.com"
)
public interface TestBaiduFeignClient
{
@GetMapping(value = "/")
String testGet();
}
【FeignRequestInterceptor.java】
package com.chz.myFeignClient.interceptor;
@Configuration
public class FeignRequestInterceptor implements RequestInterceptor
{
@Override
public void apply(RequestTemplate template)
{
// 这里给每一个FeignClient的调用增加一个header
template.header("chz-new-header", "just-for-test");
}
}
【MyFeignClientTest.java】
package com.chz.myFeignClient;
@EnableFeignClients
@SpringBootApplication
public class MyFeignClientTest
{
public static void main(String[] args) {
SpringApplication.run(MyFeignClientTest.class, args);
}
}
启动【MyFeignClientTest】,然后访问【http://localhost:8080/test/test】