《spring cloud微服务实战》读书笔记——Spring Cloud Hystrix(四)使用详解(二)

上面说了通过继承的方式来创建一个命令,并通过执行该命令调用我们封装在命令中的依赖服务调用逻辑,既然已经学会了通过继承的方式,那么下面就说一下如何通过注解的方式来实现命令的定义。

通过注解的方式完成命令的定义

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”
这里写图片描述

使用注解的方式还是要比使用继承的方式更加方便一些的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值