12、使用Feign实现接口式的远程调用服务

1.复制一个springboot消费者

image.png

我们之前是用RestTemplate做服务调用的,这回我们用Feign实现接口式的远程调用服务,那么首先我们复制之前的80消费者项目取名springcloud-consumer-dept-feign

2.添加Feign依赖

image.png

在这两个项目的pom.xml中添加依赖

 <!--feign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>

3.创建service层调用

image.png

创建DeptClientService接口

@Service
@FeignClient(value = "SPRINGCLOUD-PROVIDER-DEPT")
public interface DeptClientService {
    @GetMapping("/dept/get/{id}")
    public Dept queryById(@PathVariable("id") Long id);

    @GetMapping("/dept/list")
    public List<Dept> queryAll();

    @PostMapping("/dept/add")
    public boolean addDept(Dept dept);

}

@FeignClient(value = "SPRINGCLOUD-PROVIDER-DEPT")一行注解直接注册到了服务

4.改变调用方式
image.png

删去原来的RestTemplate

装配Feign的接口调用类

@Autowired
    private DeptClientService deptClientService;

最终使用deptClientService的方法调用服务

@RestController
@EnableEurekaClient
public class DeptConsumerController {

    @Autowired
    private DeptClientService deptClientService;

    @RequestMapping("/consumer/dept/get/{id}")
    public Dept get(@PathVariable("id") Long id){
          return this.deptClientService.queryById(id);
    }


    @RequestMapping("/consumer/dept/add")
    public boolean add(Dept dept){
        return this.deptClientService.addDept(dept);
    }

    @RequestMapping("/consumer/dept/list")
    public List<Dept> queryAll(){
        return this.deptClientService.queryAll();
    }
}

5.装配启动类

只要开启一个注解并且配置正确的扫描包即可
@EnableFeignClients(basePackages = {"com.chk.springcloud"})

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages = {"com.chk.springcloud"})
public class FeignDeptConsumer_fegin {
    public static void main(String[] args) {
        SpringApplication.run(FeignDeptConsumer_fegin.class,args);
    }
}

6.访问

image.png

访问无误,只是上一节自定义的负载均衡算法失效

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。