天天看點

MQ中的使用場景

什麼是削峰限流

1.使用場景

    秒殺活動,一般會因為流量過大,導緻應用挂掉,為了解決這個問題,一般在應用前端加入消息隊列。

作用:1.可以控制活動人數,超過此一定法治的訂單直接丢棄

           2.可以緩解短時間的高流量壓垮應用(應用程式按自己的最大處理能力擷取訂單)。

什麼是應用解耦

1.使用場景

     雙11的購物節,使用者下單後,訂單系統需要通知庫存系統,傳統的做法是訂單系統調用庫存系統的接口

缺點:當庫存系統出現故障時,訂單就失敗。

進行應用解耦。

電商平台的“秒殺搶購”:

采用“消息隊列中間件”技術,在高并發環境下充當重要角色。

如何用測試用例來做高并發

1.不是使用httpClient而是使用RestTemplate做并發。

2.先定義一個并發數200,用for循環來定200個線程

3.使用CountDownLatch來保障200個線程是并發執行而不是串行執行。

4.最後在測試用例添加seelp的目的是保障線程都能執行完成,

package com.zte.power.dexcloud.test;

import java.util.concurrent.CountDownLatch;

import org.junit.Test;
import org.springframework.web.client.RestTemplate;

@SpringBooTest(classes = TripApplication.class)
@Runwith(SpringJunit4ClassRunner.class)
public class MultithreadTest {
	private final String url = "";
	
	RestTemplate template = new RestTemplate();//不用http發請求,使用httpclient發送請求
	
	private static final int user_num = 200;//并發數,200
	
	private static CountDownLatch cdl = new CountDownLatch(user_num);
	
	
	
	@Test
	public void  TestInvoke{
		
		for(int i = 0 ;i <user_num;i++){
			new Thread(new TicketRequest()).start();
			//到目前為止都是串行執行,需要使用countDownlatch,等待來得到并發執行
			cdl.countDown();
		}
		Thread.currentThread().sleep(3000);//目的是主程式等待,使得其他線程能執行完成
        //這裡也可以使用this.join()來解決
	}
	
	public class TicketRequest implements Runnable{

		@Override
		public void run() {
			try{
				cdl.await();//
			}catch(InterruptedException e){
				e.printStackTrace();
			}
			
		}
		
		//調用http
		String result = template.getForEntity(url, String.class).getBody();
		//System.out.println(result);
	    System.out.println(result);
		
		
	}
}