1.pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2.启用
@SpringBootApplication
@EnableEurekaClient
@EnableHystrix
public class MemberServiceApplication {
@Bean
@LoadBalanced // 负载均衡注解,通过restTemplate 发送的请求默认带有负载均衡的特性(轮询)
public RestTemplate restTemplatem(){
return new RestTemplate();
}
/*
针对全局进行配置, 优先级最高
*/
@Bean
public IRule ribbonRule(){
return new RoundRobinRule();
}
public static void main(String[] args) {
SpringApplication.run(MemberServiceApplication.class, args);
}
}
3. 调用
package com.itlaoqi.springcloud.memberservice.controller;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
@RestController
public class MemberController {
@Autowired
private RestTemplate restTemplate;
/**
* RestTemplate 负载均衡 格式要求
* http://微服务id/webapi地址
*/
@RequestMapping("/sendMess")
@HystrixCommand(fallbackMethod = "sendMessFail")
public Map<String,Object> sendMess(@RequestParam("phone")String phone){
Map<String,Object> paramMap = new HashMap<>();
paramMap.put("phone",phone);
return restTemplate.getForObject("http://book-service/sendMess", Map.class,paramMap);
}
public Map<String,Object> sendMessFail(@RequestParam("phone")String phone){
Map<String,Object> paramMap = new HashMap<>();
paramMap.put("code",-1);
paramMap.put("message","发送失败");
return paramMap;
}
}