引入jar包
compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-netflix-hystrix', version: '2.2.3.RELEASE'
配置启动类
package com.server;
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;
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public class HystrixClientApplication {
public static void main(String[] args){
SpringApplication.run(HystrixClientApplication.class);
}
}
package com.server;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class TestController {
@Autowired
UrlConfig urlConfig;
@Autowired
ConsumerService consumerService;
@GetMapping("/getByUsername")
public String getByUsername() {
return consumerService.consumer();
}
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
@Component
class ConsumerService {
@Autowired
RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "fallback")
public String consumer() {
return restTemplate.getForObject(urlConfig.getServerUrl() + "/{1}",String.class,"张三");
}
public String fallback() {
return "fallback";
}
}
}
package com.server;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties
public class UrlConfig {
@Value("${service-url.server}")
private String serverUrl;
public String getServerUrl() {
return serverUrl;
}
public void setServerUrl(String serverUrl) {
this.serverUrl = serverUrl;
}
}
配置文件:
server:
port: 3030
spring:
application:
name: consume
main:
allow-bean-definition-overriding: true
cloud:
consul:
host: 127.0.0.1
port: 8500
discovery:
healthCheckPath: /
healthCheckInterval: 5s
instance-id: website-1
serviceName: m-${spring.application.name}
service-url:
server: http://server