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服务关闭,测试降级:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。