【SpringCloud】(十一):超时机制和断路器及 Hystrix简单实践

  上篇文章我们配置了Eureka集群,实现了高可用。在微服务框架中,一个服务消费者可能是其他服务消费者的提供者,而当低层次的服务提供者出现问题时,会导致系统资源被耗尽。出现雪崩效应。


Hystrix是解决解决方案的实践。



消费者服务:microservice-comsumer-movie-ribbon-withhystrix

1.POM.xml中加入依赖

	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-hystrix</artifactId>
	</dependency>

2.在启动来上加入注解:

@EnableCircuitBreaker


3.Controller中加入注解和失败调用方式

package com.dynamic.cloud.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.dynamic.cloud.entity.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

@RestController
public class MovieController {
	@Autowired
	private RestTemplate restTemplate;
	
	@GetMapping("/movie/{id}")
	@HystrixCommand(fallbackMethod = "findByIdFallback")
	public User findById(@PathVariable Long id) {
		return this.restTemplate.getForObject("http://microservice-provider-user/simple/" + id, User.class);
	}

	public User findByIdFallback(Long id) {
		User user = new User();
		user.setId(0L);				
		return user;
	}

}

4.配置文件 application.yml

server:
  port: 7901

spring:
  application:
    name: microservice-comsumer-movie-ribbon
  
eureka:
  client:
    serviceUrl:
      defaultZone: http://user:pass123@localhost:8761/eureka
  instance: 
    prefer-ip-address: true
    instance-id: ${spring.application.name}:${spring.application.instance_id:${server.port}}
#hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000

启动Eureka,用户微服务,电影微服务。

直接访问,出现数据访问成功,而当我们把用户微服务停掉的时候,再次访问就会走我们的fallbackMethod配置的方法。




评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值