Feign是一个声明式Web服务客户端,它基于Netfix Feign实现,整合了Spring Cloud Ribbon 与 Spring Cloud Hystrix,同时 Spring Cloud Feign在RestTemplate的基础上做了进一步的封装,只需创建一个接口并用注解的方式来配置它,即可完成对对服务提供方接口的绑定,简化了在使用Spring Cloud Ribbon时自行封装服务调用客户端的开发量。Spring CLoud Feign具备可插拔的注解支持,包括Feign注解和JAX-RS注解。Feign支持可插拔的编码器和解码器。Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。
搭建feign服务
1、New Model -> Spring Initializr -> Next -> Next -> Web(web)、Cloud Discovery(Eureka Discovery)、Cloud Routing(Feign) -> Next -> Finish
2、application.yml
server:
port: 5555
spring:
application:
name: client-feign
eureka:
client:
service-url:
defaultZone: http://peer1:1122/eureka/
# 这里写一个都行,因为 Eureka Server 是相互注册,高可用注册中心
3、FeignApplication:增加**@EnableDiscoveryClient,
@EnableFeignClients**注解
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication
public class FeignApplication {
public static void main(String[] args) {
SpringApplication.run(FeignApplication.class, args);
}
}
4、新建一个Interface接口:
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
@FeignClient(value = "eureka-client")//加入服务器名,不区分大小写
public interface TestFeign {
@RequestMapping("/hello")
String hello();
}
5、新建一个Controller:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Autowired
TestFeign testFeign;
@RequestMapping(value = "/hello")
public String hello(){
return testFeign.hello();
}
}
6、启动程序:多次访问:http://localhost:5555/hello 浏览器交替(和Ribbon一样,实现了负载均衡)出现:
++++++++++++++++++++OVER++++++++++++++++++++++++