Hystrix
@HystrixCommand
1.故障隔离 注解方式
Hystrix我常用到的功能是故障隔离,做为一个熔断组件,在依赖服务调用出错的时候,我们可以@HystrixCommand(fallbackMethod = "")来指定调用失败后调的方法,而不是一直阻塞
2.故障隔离 代码方式
Hystrix有一个抽象类,HystrixCommend抽象类,我们可以继承这个类,然后重写getFallback()来实现故障隔离
import org.springframework.web.client.RestTemplate;
import com.netflix.hystrix.HystrixCommand;
import com.superlighting.domain.User;
public class UserCommand extends HystrixCommand<User>{
User u;
RestTemplate restTemplate;
protected UserCommand(Setter setter,RestTemplate restTemplate,User u) {
super(setter);
this.u = u;
this.restTemplate = restTemplate;
}
@Override
protected User run() throws Exception {
return restTemplate.postForObject("http://user-service/login", u, User.class);
}
@Override
protected User getFallback(){
return new User();
}
}
3.异常处理
如果我们调用依赖服务的时候,我们知道可能会发生一些异常,而这些异常发生时我们不希望会触发服务降级的fallback(),这个时候我们可以使用@HystrixCommand(ignoreExceptions = {BadRequesException.class}),当BadRequesException异常发生时,我们忽略此异常,不走fallback().
4.异常获取
当发生一些异常,走了我们的fallback()方法时,我们想要获取异常信息,来做一些处理,这个时候我们可以在回调方法里面处理异常。
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.superlighting.domain.User;
@Service
public class HelloService {
//负载均衡
@Autowired
private RestTemplate restTemplate;
@HystrixCommand(fallbackMethod="hiError")//这个服务崩溃之后,会走HystrixCommand括号里面的方法
public User hiS(@RequestBody User u){
System.out.println(u.getUserName());
System.out.println(u.getPassword());
return restTemplate.postForObject("http://user-service/login", u, User.class);
//return restTemplate.getForObject("http://user-service/login", String.class);
}
public User hiError(@RequestBody User u, Throwable e){
System.out.println(e.getMessage());
return new User();
}
public static void main(String[] args) {
Map<String,String> map = new HashMap<>();
map.put("1","1");
System.out.println("1".hashCode());
}
}
4.请求缓存
我们调用一些依赖服务获取信息的时候,可以加入缓存,来提升返回的速度(这个表达不是很准确)
@CacheResult //加入这个注解说明开启了缓存,同时我们还可以在请求参数上面加上
//@CacheKey注解来定义缓存key,如果传入的缓存key相同,则返回缓存里面的内容
@HystrixCommand(fallbackMethod="hiError")//这个服务崩溃之后,
//会走HystrixCommand括号里面的方法
public User hiS(@RequestBody @CacheKey("id") User u){
System.out.println(u.getUserName());
System.out.println(u.getPassword());
return restTemplate.postForObject("http://user-service/login", u, User.class);
//return restTemplate.getForObject("http://user-service/login", String.class);
}
5.缓存清理
如果依赖服务后面的逻辑改变,加入了update操作的话,我们再使用缓存里面的数据可能不准确,有时候我们需要清理缓存
//清除方法hiS的缓存
@CacheRemove(commandKey = "hiS")
public User hiError(@RequestBody User u, Throwable e){
System.out.println(e.getMessage());
return new User();
}
6.请求合并