一、Feign简介
Feign 是Netflix声明式,模板化的HTTP客户端。
Spring Cloud Feign是基于Netflix feign实现,整合了Spring Cloud Ribbon和Spring Cloud Hystrix,除了提供这两者的强大功能外,还提供了一种声明式的Web服务客户端定义的方式。
Feign默认集成了Ribbon,实现负载均衡。
二、搭建服务消费者feign
<?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">
<parent>
<artifactId>mo-cloud</artifactId>
<groupId>com.mo</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>feign</artifactId>
<description>服务消费feign</description>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<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>
</dependency>
</dependencies>
</project>
server:
port: 0
spring:
application:
name: feign
eureka:
client:
service-url:
default-zone: http://127.0.0.1:8761/eureka/
instance:
prefer-ip-address: true
instance-id: ${spring.application.name}:${random.int}
package com.mo.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
/**
* feign接口
* FeignClient 表示这个接口调用哪个服务
*
* @author x.pan
* @email px5215201314@163.com
* @date 2020/4/6 21:28
*/
@FeignClient("service-hello")
public interface HelloService {
/**
* 通过feign调用指定服务
*
* @return
*/
@GetMapping("/hello")
String hello();
}
package com.mo;
import com.mo.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* EnableFeignClients 开启feign的功能
*
* @author x.pan
* @email px5215201314@163.com
* @date 2020/4/6 21:26
*/
@RestController
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class FeignApplication {
@Autowired
private HelloService helloService;
public static void main(String[] args) {
SpringApplication.run(FeignApplication.class, args);
}
/**
* 通过feign消费service-hello提供的服务
*
* @return
*/
@GetMapping("/hello")
public String hello() {
return helloService.hello();
}
}
效果:请求feign服务的hello接口,会交替显示service-hello两个服务执行结果