上面说了通过继承的方式来创建一个命令,并通过执行该命令调用我们封装在命令中的依赖服务调用逻辑,既然已经学会了通过继承的方式,那么下面就说一下如何通过注解的方式来实现命令的定义。
通过注解的方式完成命令的定义
1、使用注解的方式构建一个同步执行的命令
新建一个命令类MyHystrixCommandAnnotation,使用注解@HystrixCommand完成命令的定义
@Component
public class MyHystrixCommandAnnotation {
@Resource
RestTemplate restTemplate;
@HystrixCommand(commandKey = "helloHystrixCommandAnnotation")
public String testHystrixCommandAnnotation() throws Exception {
return restTemplate.getForEntity("http://eureka-service/command-service", String.class).getBody();
}
}
在这里@HystrixCommand注解中的commandkey如同继承方式中setter的作用,用来给命令命名。
在controller中创建一个新的方法,该方法用于当请求到达的时候,同步的执行我们刚才用注解定义的命令。
@RequestMapping(value="/helloCommandAnnotation",method = RequestMethod.GET)
@ResponseBody
public String helloCommandAnnotation() throws Exception {
String result = myHystrixCommandAnnotation.testHystrixCommandAnnotation();
return result;
}
启动项目,访问http://localhost:9000/helloCommandAnnotation 成功返回字符串”haha”
2、使用注解的方式实现命令的异步执行
异步的方式其实也很简单,只需要修改命令的定义方式即可
定义如下
@HystrixCommand(commandKey = "helloHystrixCommandAnnotation")
public Future<String> testHystrixCommandAnnotation(){
return new AsyncResult<String>() {
@Override
public String invoke() {
return restTemplate.getForEntity("http://eureka-service/command-service", String.class).getBody();
}
};
}
因为该方法的返回值是Future,所以需要在controller中对应的返回值
@RequestMapping(value="/helloCommandAnnotation",method = RequestMethod.GET)
@ResponseBody
public String helloCommandAnnotation() throws Exception {
//String result = myHystrixCommandAnnotation.testHystrixCommandAnnotation();
Future<String> stringFuture = myHystrixCommandAnnotation.testHystrixCommandAnnotation();
String result = stringFuture.get();
return result;
}
启动项目,访问http://localhost:9000/helloCommandAnnotation 成功返回字符串”haha”
使用注解的方式还是要比使用继承的方式更加方便一些的。