熔断机制是一种自我保护机制,当有大量请求堆积,服务根本无力即时处理时,熔断机制能决定丢弃请求,以保证自身资源不被耗尽而宕机,熔断器通常用在服务消费者身上,当服务调用者在单位时间内消费服务时错误次数达到设定上限,就不会调用服务消费者,转而调用设定的回调函数,Feign中集成了Hystrix,使用起来很简单,新建一个Maven Module,pom.xml如下:
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wang</groupId>
<artifactId>aServiceConsumerFeignHystrix</artifactId>
<version>1.0-SNAPSHOT</version>
<!--版本号控制-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/>
</parent>
<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>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
application.properties如下:
server.port=8883
spring.application.name=service-consumer-feign-hystrix
eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/,http://localhost:1112/eureka/
feign.hystrix.enabled=true
Controller类:
package com.wang.controller;
import com.wang.service.FeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by cheng on 2018/9/23.
*/
@RestController
public class FeignController {
@Autowired
FeignService feignService;
@GetMapping(value = "/feign")
public String feign(@RequestParam String name){
return feignService.feignFun(name);
}
}
Service接口:
@FeignClient(value="service-a",fallback = FeignServiceImpl.class)
public interface FeignService {
@RequestMapping(value="/aservice", method = RequestMethod.GET)
String feignFun(@RequestParam(value = "name") String name);
}
Service实现类:
@Component
public class FeignServiceImpl implements FeignService {
@Override
public String feignFun(String name) {
return "hystrix do " + name;
}
}
启动类:
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableFeignClients
public class ConsumerFeignHystrixApp {
public static void main(String[] args) {
SpringApplication.run(ConsumerFeignHystrixApp.class, args);
}
}