Feign是一个声明式的伪Http客户端,它使得写Http客户端变得更简单。使用Feign,只需要创建一个接口并注解。它具有可插拔的注解特性,可使用Feign 注解和JAX-RS注解。Feign支持可插拔的编码器和解码器。Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。
- Feign 采用的是基于接口的注解
- Feign 整合了ribbon,具有负载均衡的能力
- 整合了Hystrix,具有熔断的能力
启动 eureka-server 端口8761 启动eureka-client 端口8762 启动eureka-client 端口8763
这样eureka-client 在eureka-server中注册了两个实例 端口分别为8762 8763
新建服务消费者 feign-server
在主工程下新建module feign-server
在它的pom.xml继承了父pom文件,并引入了以下依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xuxu</groupId>
<artifactId>feign-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>feign-server</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>com.xuxu</groupId>
<artifactId>springcloud01</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
配置文件application.yml如下
spring:
application:
name: feign-server
server:
port: 8765
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
启动类上加入注解@EnableEurekaClient @EnableDiscoveryClient @EnableFeignClients开启Feign的功能
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@EnableDiscoveryClient
public class FeignServerApplication {
public static void main(String[] args) {
SpringApplication.run(FeignServerApplication.class, args);
}
}
定义一个feign接口,通过@ FeignClient(“服务名”),来指定调用哪个服务。
@FeignClient("eureka-client")
public interface Hello {
@RequestMapping(value = "/hi",method = RequestMethod.GET)
public String selectOneTohello(@RequestParam(value="name") String name);
}
在Web层的controller层,对外暴露一个"/hi"的API接口,通过上面定义的Feign客户端hello来消费服务。代码如下:
@RestController
public class HelloController {
//编译器报错,无视。 因为这个Bean是在程序启动的时候注入的,编译器感知不到,所以报错。
@Autowired
Hello hello;
@RequestMapping(value ="/hi")
public String hello(@RequestParam("name") String name){
return hello.selectOneTohello(name);
}
}
启动服务
查看eureka-server中的实例