1、创建Hystrix-Service服务端
引入依赖:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath/>
</parent>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<spring-cloud.version>Greenwich.SR2</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
启动类配置:
@EnableCircuitBreaker
@EnableDiscoveryClient
@SpringBootApplication
public class HystrixServiceAppRun {
public static void main(String[] args) {
SpringApplication.run(HystrixServiceAppRun.class, args);
}
}
配置文件:
spring:
application:
name: hystrix-service
server:
port: 7004
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:7001/eureka/
service-url:
order-service: http://order-service
编写一个测试接口:
@RestController
@RequestMapping("/order")
public class OrderHystrixController {
@Autowired
private OrderService orderService;
@GetMapping("/testFallback/{id}")
public CommonResult testFallbackOrder(@PathVariable Long id) {
return orderService.getOrder(id);
}
}
Service层代码:
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
private RestTemplate restTemplate;
@Value("${service-url.order-service}")
private String orderServiceUrl;
@HystrixCommand(fallbackMethod = "getDefaultOrder")
@Override
public CommonResult getOrder(Long id) {
return restTemplate.getForObject(orderServiceUrl + "/order/{1}", CommonResult.class, id);
}
public CommonResult getDefaultOrder(@PathVariable Long id) {
Order defaultOrder = new Order();
defaultOrder.setOrderId(999L);
defaultOrder.setOrderName("华为手机");
return new CommonResult<>(defaultOrder);
}
}
启动eureka-server服务
启动order-service服务
启动hystrix-service服务
2、接口测试
调用此接口:[http://localhost:7004/order/testFallback/1](http://localhost:7004/order/testFallback/1)
然后将Order-service服务关闭,测试降级: