服务调用

服务调用

起男 900 2021-08-22

服务调用

feign是spring cloud提供的一个声明式的伪http客户端,它使得调用远程服务就像调用本地服务一样简单,只需要创建一个接口并添加一个注解即可

nacos很好的兼容了feign,feign默认集成了ribbon,所以在nacos下使用fegin默认就实现了负载均衡的效果

使用

  1. 导入依赖

    		<dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-openfeign</artifactId>
            </dependency>
    
  2. 启动类添加注解@EnableFeignClients

  3. 创建一个service,并使用feign实现服务调用

    @FeignClient("被调用服务名称")
    public interface FeignService {
    
        @GetMapping("{id}")
        Object findByPid(@PathVariable Integer id);
    }
    
  4. 使用,就像调用本地接口一样

    @Resource
    private FeignService feignService;