新聞中心
前言
在高并發(fā)的場景下,前端會(huì)有大量的訪問請求。如果一個(gè)請求就需要打開一個(gè)數(shù)據(jù)庫連接,操作完數(shù)據(jù)庫后再進(jìn)行關(guān)閉,無形中對數(shù)據(jù)造成很大的開銷。請求合并是將多個(gè)單個(gè)請求合并成一個(gè)請求,去調(diào)用服務(wù)提供者提供的服務(wù)接口,再遍歷合并的結(jié)果為每個(gè)合并前的單個(gè)請求設(shè)置返回結(jié)果。Spring Cloud通過Hystrix實(shí)現(xiàn)請求合并,減輕高并發(fā)時(shí)的請求線程消耗、降低請求響應(yīng)時(shí)間的效果。今天就來聊一聊Hystrix請求合并的實(shí)現(xiàn)方式。

成都創(chuàng)新互聯(lián)公司是一家集網(wǎng)站建設(shè),杭州企業(yè)網(wǎng)站建設(shè),杭州品牌網(wǎng)站建設(shè),網(wǎng)站定制,杭州網(wǎng)站建設(shè)報(bào)價(jià),網(wǎng)絡(luò)營銷,網(wǎng)絡(luò)優(yōu)化,杭州網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強(qiáng)企業(yè)競爭力??沙浞譂M足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時(shí)我們時(shí)刻保持專業(yè)、時(shí)尚、前沿,時(shí)刻以成就客戶成長自我,堅(jiān)持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實(shí)用型網(wǎng)站。
實(shí)現(xiàn)方式
由于是高并發(fā)場景,因此準(zhǔn)備了SpringCloud微服務(wù)框架。準(zhǔn)備了注冊中心、網(wǎng)關(guān)、服務(wù)提供者、服務(wù)消費(fèi)者等組件。
導(dǎo)入依賴
org.springframework.cloud
spring-cloud-starter-netflix-hystrix
啟動(dòng)類上增加注解
@SpringBootApplication
@EnableHystrix
public class ServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceApplication.class, args);
}
}
實(shí)現(xiàn)請求合并,Service中代碼如下:
//請求合并的方法 合并5s內(nèi)的請求
@HystrixCollapser(batchMethod = "mergeGet", scope = com.netflix.hystrix.HystrixCollapser.Scope.GLOBAL, collapserProperties = {@HystrixProperty(name = "timerDelayInMilliseconds", value = "5000")})
public Future- get(String id) {
log.info("======執(zhí)行了get方法========" + id);
return null;
}
//合并請求之后調(diào)用的方法
@HystrixCommand
public List- mergeGet(List
ids) {
log.info("===合并開始===");
List- items = ids.stream().map(
x -> {
Item item = new Item();
item.setId(Integer.valueOf(x));
item.setName("商品 :" + x);
return item;
}
).collect(Collectors.toList());
log.info("===合并結(jié)束,合并 {} 條 請求====", ids.size());
return items;
}
?說明:調(diào)用get方法,如果5s內(nèi)get有多次調(diào)用,則合并后mergeGet方法。
controller調(diào)用代碼如下:
@RequestMapping(value = "/find/{id}")
public Item find(@PathVariable String id) throws InterruptedException, ExecutionException {
HystrixRequestContext context = HystrixRequestContext.initializeContext();
Future- items = itemService.get(id);
System.out.println(items.get());
context.close();
return items.get();
}
執(zhí)行
執(zhí)行127.0.0.1:8080/find/11,同時(shí)執(zhí)行127.0.0.1:8080/find/22,保證兩個(gè)請求在5s內(nèi)發(fā)出。
返回結(jié)果
說明:
- scope = com.netflix.hystrix.HystrixCollapser.Scope.GLOBAL:將所有線程中多次服務(wù)調(diào)用進(jìn)行合并
- scope = com.netflix.hystrix.HystrixCollapser.Scope.REQUEST:對一次請求的多次服務(wù)調(diào)用進(jìn)行合并
文章名稱:SpringCloudHystrix高并發(fā)下實(shí)現(xiàn)請求合并
文章地址:http://www.fisionsoft.com.cn/article/cdpjjsg.html


咨詢
建站咨詢
