一、Feign定义
Feigin是服务消费者,Feign是一个声明式的伪Http客户端,它使得写Http客户端变得更简单。使用Feign,只需要创建一个接口并注解。它具有可插拔的注解特性,可使用Feign 注解和JAX-RS注解。Feign支持可插拔的编码器和解码器。feign集成了Ribbon,利用Ribbon维护了MicroServiceCloud-Dept的服务列表信息,并且通过轮询实现了客服端的负载均衡.而与Ribbon不同的是,通过feign只需要定义服务绑定接口声明式的方法,优雅而简单的实现了服务调用
简而言之:是一个声明式的web服务客户端,使得Web服务端变得非常容易,只需要创建一个接口,然后在上面添加注解即可就是:接口+注解,获取调用我们的微服务---接口编程
Feign接口编程
二、Feign操作
1、修改microservicecloud-api
pom文件添加依赖
<!-- feign远程调用 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
新建一个DeptClientService 接口
@FeignClient(name = "MICROSERVICECLOUD-DEPT")//name是一个服务名称,在注册中上面
public interface DeptClientService { @RequestMapping(value = "/dept/findAll",method = RequestMethod.GET) public List<Dept> findAll(); }
2、创建microservicecloud-consumer-dept-feign工程
pom文件
<dependencies>
<!-- 引入自己定义的api通用包,可以使用Dept部门Entity -->
<dependency>
<groupId>com.yehui</groupId>
<artifactId>microservicecloud-api</artifactId>
<version>${project.version}</version>
<scope>compile</scope>
</dependency>
<!--eureka-server服务端-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
yml文件
server: port: 8087 eureka: client: register-with-eureka: true service-url: defaultZone: http://localhost:7002/eureka/,http://localhost:7003/eureka/,http://localhost:7001/eureka/
fetch-registry: true spring: application: name: ConSumeAppStartDeptfeign
创建一个controller
@RestController public class DeptController { @Autowired private DeptClientService deptClientService; @RequestMapping("/dept/list") public List<Dept> findAll() { return deptClientService.findAll(); } }
创建启动类
@SpringBootApplication @EnableFeignClients(basePackages = "com.yehui.feign")//扫描feignClient提供接口的包
public class ConSumeAppStartDeptfeign { public static void main(String[] args) { SpringApplication.run(ConSumeAppStartDeptfeign.class); } }
启动测试:
启动3个eureka集群
启动3个微服务8001/8002/8003
启动Feign自己启动
Feign自带负载均衡配置顶:
Feign通过接口的方法调用Rest服务(之前是Ribbon+RestTemplate),该请求发送给Eureka服务器(),通过Feign直接找到服务接口,由于在进行服务调用的时候融合了Ribbon技术,所以也支持负载均衡作用
测试访问路径http://localhost:8087/dept/list