改造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!