Feign

87 阅读1分钟

Feign简介

用于服务之间的调用,简单来说就是RestTemplate的替代。

OpenFeign是Feign的扩展,更多的使用的还是OpenFeign。

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

OpenFeign的使用步骤

1主启动添加@EnableFeignClients

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

2 建立访问远程服务的接口

restTemplate.getForObject("http://springcloud-nacos-provider/call/" + name, String.class); 使用restTemplate请求远程服务的时候,需要提供服务名称,请求路径和参数,已经响应类型。

Component//value为远程服务名称
//path对于远程服务Controller类上的@RequestMapping路径。如果没有则不用指定
@FeignClient(value = "CLOUD-PAYMENT-SERVICE",path="")
public interface PaymentFeignService
{

//============同时注意@PathVariable形式的参数,则要用value=""标明对应的参数,否则会抛出IllegalStateException异常
//=========同理在使用@RequestParam传递参数的时候,也要使用value属性指定名称,否则也会报错
 
 //远程服务Controller中的方法怎么写,这里就怎么写。
    @GetMapping("/search")
    public User  searchUser(int userId)
}

3依赖注入

@Autowired
PaymentFeignService paymentFeignService
//直接调用远程服务的方法。就像在调用本地方法一样
paymentFeignService.searchUser(1);