Spring cloud Hystrix快速入门示例

一 架构图

Spring cloud Hystrix快速入门示例_第1张图片

二 消费者服务ribbon-consumer

1 增加依赖,增加spring-cloud-starter-hystrix依赖


    org.springframework.cloud
    spring-cloud-starter-hystrix

2 启动类编写,增加@EnableCircuitBreaker注解

package com.didispace;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@EnableCircuitBreaker
@EnableDiscoveryClient
@SpringBootApplication
public class ConsumerApplication {

    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }

}

3 增加HelloService类

package com.didispace.web;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

@Service
public class HelloService {
    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "helloFallback")
    public String hello() {
        return restTemplate.getForEntity("http://HELLO-SERVICE/hello", String.class).getBody();
    }

    public String helloFallback() {
        return "error";
    }

}

4 控制器类编写

package com.didispace.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ConsumerController {

    @Autowired
    HelloService helloService;

    @RequestMapping(value = "/ribbon-consumer", method = RequestMethod.GET)
    public String helloConsumer() {
        return helloService.hello();
    }

}

三 测试

1 启动Eureka、启动2个Hello-Service服务,启动1个ribbon-consumer服务

Spring cloud Hystrix快速入门示例_第2张图片

2 访问http://localhost:9000/ribbon-consumer

Spring cloud Hystrix快速入门示例_第3张图片

并且Hello-Service两个服务轮询

3 关闭其中一个服务

4 访问http://localhost:9000/ribbon-consumer

浏览器结果为如下,结果轮询,说明回退生效。

error

或者

Hello World

 

 

 

 

 

 

你可能感兴趣的:(微服务)