Hystrix原理:
Hystrix原理.pngHystrix使用:
使用方式一:自定义Hystrix请求命令的方式
Spring Cloud中Hystrix的请求缓存 - 个人文章 - SegmentFault 思否
hystrix缓存功能的使用 - CSDN博客
通过方法重载开启缓存
com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect
com.netflix.hystrix.HystrixCommand
public class BookCommand extends HystrixCommand<Book> {
private RestTemplate restTemplate;
private Long id;
@Override
protected Book getFallback() {
Throwable executionException = getExecutionException();
System.out.println(executionException.getMessage());
return new Book("宋诗选注", 88, "钱钟书", "三联书店");
}
@Override
protected Book run() throws Exception {
return restTemplate.getForObject("http://HELLO-SERVICE/getbook5/{1}", Book.class,id);
}
public BookCommand(Setter setter, RestTemplate restTemplate,Long id) {
super(setter);
this.restTemplate = restTemplate;
this.id = id;
}
@Override
protected String getCacheKey() {
return String.valueOf(id);
}
}
BookCommand bc1 = new BookCommand(HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("")).andCommandKey(commandKey), restTemplate, 1l);
Book e1 = bc1.execute();
@RequestMapping("/test5")
public Book test5() {
HystrixCommandKey commandKey = HystrixCommandKey.Factory.asKey("commandKey");
HystrixRequestContext.initializeContext();
BookCommand bc1 = new BookCommand(HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("")).andCommandKey(commandKey), restTemplate, 1l);
Book e1 = bc1.execute();
BookCommand bc2 = new BookCommand(HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("")).andCommandKey(commandKey), restTemplate, 1l);
Book e2 = bc2.execute();
BookCommand bc3 = new BookCommand(HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("")).andCommandKey(commandKey), restTemplate, 1l);
Book e3 = bc3.execute();
System.out.println("e1:" + e1);
System.out.println("e2:" + e2);
System.out.println("e3:" + e3);
return e1;
}
Spring boot使用
@EnableCircuitBreaker
@EnableDiscoveryClient
@SpringBootApplication
public class ConsumerApplication {
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.*run*(ConsumerApplication.class, args);
}
}
@Service
public class UserService {
@Autowired
RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "userFallback", commandKey = "userKey")
public User user(String name) {
User user = restTemplate.getForEntity("http://HELLO-SERVICE/hello1?name={1}", User.class, name).getBody();
return user;
}
public String userFallback() {
return "error";
}
}
参考
Hystrix基于RxJava的异步执行模式 - CSDN博客
How it Works · Netflix/Hystrix Wiki · GitHub
Hystrix浅入浅出:(二)断路器和滑动窗口 - CSDN博客
网友评论