改造Eureka + Ribbon + RestTemplate 負載均衡 點擊進入查看
Step 3-1:添加依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
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!";
}
}
-
啓動後效果:訪問 http://localhost:8764/hi?name=forezp
瀏覽器交替顯示:
hi forezp,i am from port:8762
hi forezp,i am from port:8763
- 關閉SERVICE-HI:訪問 http://localhost:8764/hi?name=forezp
瀏覽器顯示:
hi,forezp,sorry,error!