電子商務(wù)網(wǎng)站建設(shè)應(yīng)該側(cè)重哪方面網(wǎng)站優(yōu)化方法
jd19支持虛擬線程,虛擬線程是輕量級(jí)的線程,它們不與操作系統(tǒng)線程綁定,而是由 JVM 來管理。它們適用于“每個(gè)請(qǐng)求一個(gè)線程”的編程風(fēng)格,同時(shí)沒有操作系統(tǒng)線程的限制。我們能夠創(chuàng)建數(shù)以百萬計(jì)的虛擬線程而不會(huì)影響吞吐。
做個(gè) springboot demo 嘗試一下。
環(huán)境
- jdk19
- gradle 7.6.1
- IntelliJ IDEA 2022.2.4
build.gradle
plugins {id 'java'id 'org.springframework.boot' version '3.0.3'id 'io.spring.dependency-management' version '1.1.0'
}group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '19'configurations {compileOnly {extendsFrom annotationProcessor}
}repositories {mavenCentral()
}dependencies {implementation 'org.springframework.boot:spring-boot-starter'compileOnly 'org.projectlombok:lombok'developmentOnly 'org.springframework.boot:spring-boot-devtools'annotationProcessor 'org.projectlombok:lombok'testImplementation 'org.springframework.boot:spring-boot-starter-test'
}tasks.named('test') {useJUnitPlatform()
}tasks.withType(JavaCompile) {options.compilerArgs += "--enable-preview"
}
多線程demo
寫一段多線程調(diào)用的代碼,程序入口
package com.example.myvirtualthreaddemo;import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.core.task.support.TaskExecutorAdapter;
import org.springframework.scheduling.annotation.EnableAsync;import java.util.concurrent.Executors;@EnableAsync
@SpringBootApplication
public class MyVirtualThreadDemoApplication {public static void main(String[] args) {SpringApplication.run(MyVirtualThreadDemoApplication.class, args);}@BeanCommandLineRunner commandLineRunner(AsyncService asyncService){return args -> {for(int i = 0; i < 100; i++){asyncService.fun(i);}};}
}
package com.example.myvirtualthreaddemo;import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;@Service
@Slf4j
public class AsyncService {@Asyncpublic void fun(int i) {log.info("fun:{}", i);}
}
運(yùn)行結(jié)果,使用平臺(tái)線程(默認(rèn)8個(gè))
使用虛擬線程
在MyVirtualThreadDemoApplication添加以下代碼塊
@Bean(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME)public AsyncTaskExecutor asyncTaskExecutor(){return new TaskExecutorAdapter(Executors.newVirtualThreadPerTaskExecutor());}
運(yùn)行結(jié)果,使用虛擬線程
遇到的一些問題
請(qǐng)使用 --enable-preview 以啟用預(yù)覽 API
解決辦法:
- build.gradle里添加以下配置:
tasks.withType(JavaCompile) {options.compilerArgs += "--enable-preview"
}
- 設(shè)置vm選項(xiàng)如圖