如何提升SpringBoot服務吞吐量?

### 背景 ###

生產環境偶爾會有一些慢請求導致系統性能下降,吞吐量下降,下面介紹幾種優化建議。

### 方案 ###

1、undertow替換tomcat

電子商務類型網站大多都是短請求,一般響應時間都在100ms,這時可以將web容器從tomcat替換爲undertow,下面介紹下步驟:

1.1、增加pom配置

<!-- undertow替換tomcat -->
		<dependency>
		    <groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
			<exclusions>
				<exclusion>
					<groupId>org.springframework.boot</groupId>
					<artifactId>spring-boot-starter-tomcat</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
		    <groupId>org.springframework.boot</groupId>
		    <artifactId>spring-boot-starter-undertow</artifactId>
		</dependency>

1.2、增加相關配置

# 設置IO線程數, 它主要執行非阻塞的任務,它們會負責多個連接, 默認設置每個CPU核心一個線程
server.undertow.io-threads=8
# 阻塞任務線程池, 當執行類似servlet請求阻塞操作, undertow會從這個線程池中取得線程,它的值設置取決於系統的負載
server.undertow.worker-threads=64
# 以下的配置會影響buffer,這些buffer會用於服務器連接的IO操作,有點類似netty的池化內存管理
# 每塊buffer的空間大小,越小的空間被利用越充分
server.undertow.buffer-size=1024
# 是否分配的直接內存
server.undertow.direct-buffers=true

重新啓動可以在控制檯看到容器已經切換爲undertow了。

2、緩存

將部分熱點數據或者靜態數據放到本地緩存或者redis中,如果有需要可以定時更新緩存數據。

3、異步

在代碼過程中我們很多代碼都不需要等返回結果,也就是部分代碼是可以並行執行,這個時候可以使用異步,最簡單的方案是使用springboot提供的@Async註解,當然也可以通過線程池來實現,下面簡單介紹下異步步驟。

3.1、pom依賴 一般springboot引入web相關依賴就行

<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-web</artifactid>
</dependency>

3.2、在啓動類中增加@EnableAsync註解

@EnableAsync
@SpringBootApplication
public class AppApplication{
    public static void main(String[] args){
        SpringApplication.run(AppApplication.class, args);
    }
}

3.3、需要時在指定方法中增加@Async註解

如果是需要等待返回值,則demo如下

@Async
public Future<string> doReturn(int i){
    try {
        // 這個方法需要調用500毫秒
         Thread.sleep(500);
     } catch (InterruptedException e) {
       e.printStackTrace();
    }
    / 消息彙總
    return new AsyncResult&lt;&gt;("異步調用");
}

3.4、如果有線程變量或者logback中的mdc,可以增加傳遞

import org.slf4j.MDC;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskDecorator;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.Map;
import java.util.concurrent.Executor;

/**
 * @Description:
 */
@EnableAsync
@Configuration
public class AsyncConfig extends AsyncConfigurerSupport {
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setTaskDecorator(new MdcTaskDecorator());
        executor.initialize();
        return executor;
    }
}

class MdcTaskDecorator implements TaskDecorator {

    @Override
    public Runnable decorate(Runnable runnable) {
        Map<string, string> contextMap = MDC.getCopyOfContextMap();
        return () -&gt; {
            try {
                MDC.setContextMap(contextMap);
                runnable.run();
            } finally {
                MDC.clear();
            }
        };
    }
}

3.5、有時候異步需要增加阻塞

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@Slf4j
public class TaskExecutorConfig {

    @Bean("localDbThreadPoolTaskExecutor")
    public Executor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(5);
        taskExecutor.setMaxPoolSize(200);
        taskExecutor.setQueueCapacity(200);
        taskExecutor.setKeepAliveSeconds(100);
        taskExecutor.setThreadNamePrefix("LocalDbTaskThreadPool");
        taskExecutor.setRejectedExecutionHandler((Runnable r, ThreadPoolExecutor executor) -&gt; {
                    if (!executor.isShutdown()) {
                        try {
                            Thread.sleep(300);
                            executor.getQueue().put(r);
                        } catch (InterruptedException e) {
                            log.error(e.toString(), e);
                            Thread.currentThread().interrupt();
                        }
                    }
                }
        );
        taskExecutor.initialize();
        return taskExecutor;
    }

}

4、業務拆分

可以將比較耗時或者不同的業務拆分出來提供單節點的吞吐量

5、集成消息隊列

有很多場景對數據實時性要求不那麼強的,或者對業務進行業務容錯處理時可以將消息發送到kafka,然後延時消費。舉個例子,根據條件查詢指定用戶發送推送消息,這裏可以時按時、按天、按月等等。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章