Feign是一个声明式的伪Http客户端,它使得写Http客户端变得更简单。使用Feign,只需要创建一个接口并注解。它具有可插拔的注解特性,可使用Feign 注解和JAX-RS注解。Feign支持可插拔的编码器和解码器。Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。
新建项目 引入 pom依赖
<!--Eureka服务-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
<!--feign依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
yml文件3步走
#1.先给这个服务起一个名字
spring:
application:
name: service-feign
#2.给定一个指定的端口号
server:
port: 8765
#ssss 注册中心地址:
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/eureka
package com.tg.feign_demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableEurekaClient//激活eureka客户端
@EnableFeignClients//激活Feign
public class FeignDemoApplication {
public static void main(String[] args) {
SpringApplication.run( FeignDemoApplication.class, args );
}
}
package com.tg.feign_demo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
//FeignClient 直接定义该当前接口对应的注册中心 的服务名 用于指定调用哪一个服务
@FeignClient(value = "EUREKA-CLIENT")
public interface RestHiService {
//对应的服务中心的服务方法
@GetMapping(value = "/hi")
public String sayHi();
}
package com.tg.feign_demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@org.springframework.web.bind.annotation.RestController
public class RestController {
@Autowired
RestHiService restHiService;
@RequestMapping(value = "/hi", method = RequestMethod.GET)
public String sayHi() {
return restHiService.sayHi();
}
}