openFeign简介

openFeign使用

在消费者pom.xml引入如下依赖

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

在启动类上加注解@EnableFeignClients

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class NacosConsumer {
public static void main(String[] args) {
SpringApplication.run(NacosConsumer.class,args);
}
}

在服务提供者中有这样一个controller

@RestController
public class ProviderController {
@RequestMapping("/hello")
public String helloNacos(){
return "hello world";
}
}

在服务消费者中新建一个接口service,其中nacos-provider就是服务提供者中spring.application.name的值,/hello就是服务提供者中Controller@RequestMapping("/hello")的值

@Component
@FeignClient(name = "nacos-provider")
public interface ConsumerService {
@GetMapping(value = "/hello")
String helloNacos();
}

在服务消费者controller中调用

@RestController
public class ConsumerController {
@Autowired
private ConsumerService consumerService;

@GetMapping(value = "/helloFeign")
public String getPayById(){
return consumerService.helloNacos();
}
}

测试:http://localhost:8083/helloFeign

页面输出:hello world

feign自带负载均衡