Feign是声明式WebService客户端,它让服务之间的调用变的更加简单。Feign默认底层使用的是ribbon客户端,所以具有负载均衡的功能,并且Feign整合了Hystrix,具备熔断的功能。
Feign is a declarative web service client. It makes writing web service clients easier. To use Feign create an interface and annotate it. It has pluggable annotation support including Feign annotations and JAX-RS annotations.
基于上一节学习笔记的ribbon工程,在Consumer工程里POM里加入依赖文件:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
在启动类上加上@EnableFeignClients注解开启Feign的功能:
package org.dothwinds.serviceconsumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class SpringCloudStudyServiceConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudStudyServiceConsumerApplication.class, args);
}
//注入restTemplate
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
指定一个接口,加上feign的注解,指定需要调用的服务及调用方式
package org.dothwinds.serviceconsumer.serviceinterface;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
//FeignClient需要调用的服务
@FeignClient("service-provider")
public interface ServiceConsumerInterface {
@GetMapping(value = "/testLoadBalance")
public String serviceCousumer();
}
在Controller里改写一下原来的方法测试一下我们feign的客户端是否好用
package org.dothwinds.serviceconsumer.controller;
import org.dothwinds.serviceconsumer.serviceinterface.ServiceConsumerInterface;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class ServiceConsumerController {
@Autowired
private RestTemplate restTemplate;
@Autowired
private ServiceConsumerInterface serviceConsumerInterface;
@GetMapping("/testLoadBalance")
public String serviceCousumer(){
// return restTemplate.getForObject("http://SERVICE-PROVIDER/service", String.class);
serviceConsumerInterface.serviceCousumer();
}
}
接下来我们来测试一下,访问testLoadBalance,看一下是否有效果,重复刷新页面地址:


参考资料:
参考资料:https://cloud.spring.io/spring-cloud-static/Greenwich.SR5/single/spring-cloud.html
代码地址:https://gitee.com/dothwinds/Spring-Cloud-Study/tree/master/spring-cloud-study-ribbon
本文介绍Feign声明式WebService客户端的使用方法,通过创建接口并注解,简化服务间调用。Feign整合了Ribbon和Hystrix,具备负载均衡和熔断功能。文章详细展示了如何在Spring Cloud项目中引入Feign,实现服务调用。
457

被折叠的 条评论
为什么被折叠?



