Hystrix整合Resttemplate

文章目录

    • 启动类
    • MainController.java
    • RestService.java

启动类

启动类加上 @EnableCircuitBreaker 注解(Hystrix整合Feign时,不需要加次注解)

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

@SpringBootApplication
@EnableFeignClients
@EnableCircuitBreaker
public class UserConsumerApplication {

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

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

MainController.java

    @Autowired
    RestService restService;

    @GetMapping("/alive2")
    public String alive2(){
        return restService.alive();
    }

RestService.java

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class RestService {

    @Autowired
    RestTemplate template;

    @HystrixCommand(defaultFallback = "back")
    public String alive() {

        String url = "http://user-provider/alive";

        String forObject = template.getForObject(url, String.class);

        return forObject;
    }

    public String back(){
        return "back";
    }
}

你可能感兴趣的:(Spring,Cloud,Hystrix)