SpringCloud服务消费者rest + ribbon + hystrix
在父工程目录下创建一个maven项目,在这个maven项目中添加依赖
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
</dependencies>
在配置文件application.yml中添加以下配置
eureka:
client:
serviceUrl:
defaultZone: http://localhost:7010/eureka/
server:
port: 8777
spring:
application:
name: ribbon-service
management:
endpoints:
web:
exposure:
include: hystrix.stream
endpoint:
health:
show-details: always
启动类
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableHystrix
public class RibbonApplication {
public static void main(String[] args) {
SpringApplication.run( RibbonApplication.class, args );
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
Web层
@Controller
public class RemoteRibbon {
@Autowired
RemoteService remoteService;
@GetMapping("/hi")
public String hi(@RequestParam String name) {
return remoteService.hiService(name);
}
}
service层
@Service
public class RemoteService {
@Autowired
RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "hiError")
public String hiService(String name) {
String forObject = restTemplate.getForObject("http://server02/hi?name=" + name, String.class);
System.out.println(forObject);
return forObject;
}
public String hiError(String name) {
return "Hystrix:" + name;
}
}
依次启动Eureka、config-server、再启动本服务
在浏览器上访问http://localhost:8777/hi?name=啊啊啊 ,返回服务提供者的值
关闭服务提供者服务,再次访问返回Hystrix: 啊啊啊