Feign使用

feign特点

和ribbon一样feign也可以作微服务的负载均衡,使用feign来调用的api接口让api接口更像是本地的接口

源代码

 yaml 配置
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
server:
  port: 8765
spring:
  application:
    name: service-feign
feign.hystrix.enabled: true
pom 配置
<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>
	<parent>
		<groupId>com.example</groupId>
		<artifactId>spring-cloud-eureka-master</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<artifactId>spring-cloud-eureka-feign</artifactId>

	<dependencies>
		<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>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-openfeign</artifactId>
		</dependency>
	</dependencies>
</project>
java 代码如下
/**
 * 
 * 一个服务注册中心,eureka server,端口为8761 service-hi工程跑了两个实例,端口分别为8762,8763,分别向服务注册中心注册
 * sercvice-ribbon端口为8764,向服务注册中心注册
 * 当sercvice-ribbon通过restTemplate调用EURKA-CLIENT的hi接口时,
 * 因为用ribbon进行了负载均衡,会轮流的调用EURKA-CLIENT:8762和8763 两个端口的hi接口;
 */

// feign 自带了hystrix ,只需要开启hystrix功能就可以了:feign.hystrix.enabled=true
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableFeignClients
public class ServiceFeignApplication {

	public static void main(String[] args) {
		SpringApplication.run(ServiceFeignApplication.class, args);
	}

	@Bean
	@LoadBalanced
	RestTemplate restTemplate() {
		return new RestTemplate();
	}

}

/**
* 通过feign 获取eurka-client服务提供的api接口
*/
@FeignClient(value = "eurka-client",fallback = SchedualServiceHiHystric.class)
public interface ScheduleService {

	@RequestMapping(value = "/hi", method = RequestMethod.GET)
	String sayHi(@RequestParam(value = "name") String name);

}


@Component
public class SchedualServiceHiHystric implements ScheduleService {
    @Override
    public String sayHi(String name) {
        return "sorry "+name;
    }
}

@RestController
public class HelloControler {

	// 编译器报错,无视。 因为这个Bean是在程序启动的时候注入的,编译器感知不到,所以报错。
	@Autowired
	ScheduleService schedualService;

	@GetMapping(value = "/hi")
	public String sayHi(@RequestParam String name) {
		return schedualService.sayHi(name);
	}
}