5 Feign
5.1 是什么
- Feign和Ribbon都是Spring Cloud Netflix 中的负载均衡的组件。和Ribbon不同的是,使用Feign可以向我们使用Java中的接口一样方便
- Feign方便之处
- 通常,服务的调用分散在各个地方。如果我们使用Ribbon的话,如果说我们需要管理这些调用(维护、更换。。。),那么我们需要修改程序之中的每一处
- 但是Feign则不一样。我们使用接口的方式进行调用,那么修改一处就好了
5.2 集成Feign
1)pom.xml
<dependencies>
<dependency>
<groupId>springcloud</groupId>
<artifactId>API</artifactId>
<version>1.0.0</version>
</dependency>
<!--web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--eureka-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--feign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.2.7.RELEASE</version>
</dependency>
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
</dependency>
<!--devtools-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>
2)application.yaml
server:
port: 80
spring:
application:
name: consumer-feign-80
eureka:
client:
register-with-eureka: false # 作为消费者,不需要向注册中心注册自己
fetch-registry: true # 但是作为消费者,需要从注册中心中拉去服务信息
service-url:
defaultZone: http://eureka7000:7000/eureka/, http://eureka7001:7001/eureka/, http://eureka7002:7002/eureka/, http://eureka7003:7003/eureka/, http://eureka7004:7004/eureka/
3)启动类
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients("com.pbx.springcloud") // 扫描feign的注解
public class FeignConsumer {
public static void main(String[] args) {
SpringApplication.run(FeignConsumer.class, args);
}
}
4)FeignService
@Service // 把Feign注册到Spring容器中
@FeignClient("PROVIDER-EUREKA") // 配置要访问的服务名
@RequestMapping("/provider")
public interface FeignService {
@PostMapping("/add")
Message add(Department department);
@GetMapping("/get/{id}")
Message getDepartmentById(@PathVariable("id") Long id);
@GetMapping("/get/all")
Message getDepartmentList();
}
5)改造Controller
@RestController
@RequestMapping("/consumer")
@Slf4j
public class ConsumerController {
@Autowired
private FeignService service; // 这就回到了我们熟系的方式了
@RequestMapping("/add")
public Message add(Department department) {
return service.add(department);
}
@RequestMapping("/get/{id}")
public Message getDepartmentById(@PathVariable("id") Long id) {
return service.getDepartmentById(id);
}
@RequestMapping("/get/all")
public Message getDepartmentList() {
return service.getDepartmentList();
}
}
6)测试