Spring cloud hystrix合并请求

一 新建合并请求控制器

package org.crazyit.cloud.collapser;

import java.util.concurrent.Future;

import org.crazyit.cloud.Member;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CollController {
    
    @Autowired
    private CollService collService;

    @RequestMapping(value = "/coll", method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public String testCollapse() throws Exception {
        // 连续执行3次请求
        Future<Member> f1 = collService.getMember(1);
        Future<Member> f2 = collService.getMember(2);
        Future<Member> f3 = collService.getMember(3);
        Member p1 = f1.get();
        Member p2 = f2.get();
        Member p3 = f3.get();    
        return "";
    }
}

二 新建合并请求服务

package org.crazyit.cloud.collapser;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

import org.crazyit.cloud.Member;
import org.springframework.stereotype.Service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;

@Service
public class CollService {

    @HystrixCollapser(batchMethod = "getMembers", collapserProperties = {
            @HystrixProperty(name = "timerDelayInMilliseconds", value = "1000")
    })
    public Future<Member> getMember(Integer id) {
        System.out.println("执行单个查询的方法");
        return null;
    }
    
    @HystrixCommand
    public List<Member> getMembers(List<Integer> ids) {
        List<Member> mems = new ArrayList<Member>();
        for(Integer id : ids) {
            System.out.println(id);
            Member m = new Member();
            m.setId(id);
            m.setName("angus");
            mems.add(m);
        }
        return mems;
    }
}

三 启动服务

四 浏览器输入http://localhost:8081/coll

控制台输出结果如下,符合预期。

2

3

1

五 请求缓存的优势

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值