Eureka + Ribbon + RestTemplate + Hystrix (使用熔断器Hystrix )

改造Eureka + Ribbon + RestTemplate 负载均衡  点击进入查看

Step 3-1:添加依赖

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

 

注:不熟悉如何搭建Spring Boot 项目,请点击

 

Step 3-2:编写启动类@EnableHystrix,开启熔断器

@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix
public class ServiceRibbonApplication {

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

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

}

 Step 3-3:改造Service 

@Service
public class HelloService {

    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "hiError")
    public String hiService(String name) {
        return restTemplate.getForObject("http://SERVICE-HI/hi?name="+name,String.class);
    }

    public String hiError(String name) {
        return "hi,"+name+",sorry,error!";
    }

}

浏览器交替显示:

hi forezp,i am from port:8762

hi forezp,i am from port:8763

浏览器显示:

hi,forezp,sorry,error!

 

 
posted @ 2019-08-14 11:35  随风落木  阅读(0)  评论(0编辑  收藏  举报  来源