140、spring webflux 高併發的spring組件

 

 

 

最近公司可謂是風雲變幻,年前說要拆開賣,後來講要總體賣,表示像我這種渣渣,始終逃脫不掉被賣的命運java

下面進入正題react

spring webflux 是spring 支持的高併發web框架,將每一個http請求都以java nio的非阻塞方式來進行處理git

這樣當cpu在處理一個請求的空隙時,還有時間來處理其餘請求。提升CPU資源的運行效率github

下面來看如何進行實現web

一、首先eclipse中新建一個maven的項目。而後完整版的pom文件以下所示。(本人翻遍了網上的教程,都沒有提供完整版的pom文件,哪裏有?哪裏有?感受這裏是獨一份,除了github之外)spring

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    
  <groupId>Pactera</groupId>
  <artifactId>webflux-test</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>webflux-test</name>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
  </properties>
  
   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.BUILD-SNAPSHOT</version>
        <relativePath/>
   </parent>
   

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    
    

    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.projectreactor</groupId>
        <artifactId>reactor-test</artifactId>
        <scope>test</scope>
    </dependency>
  </dependencies>
  
       <build>
              <defaultGoal>compile</defaultGoal>
        <plugins>  
            <plugin>  
                <artifactId>maven-jar-plugin</artifactId>  
                <executions>  
                    <execution>  
                        <!-- <goals>  
                            <goal>jar</goal>  
                        </goals>   -->
                        <phase>package</phase>  
                    </execution>  
                </executions>  
            </plugin> 
            <!-- <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin> -->
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
    
  
  
</project>

二、下面是一個handler處理類,這個類是用來處理http請求的核心類apache

package org.spring.springboot.handler;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

@Component
public class CityHandler {
    
    public Mono<ServerResponse> helloCity(ServerRequest request) {
        return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN)
                .body(BodyInserters.fromObject("Hello, City!"));
    }
    
}

三、下面一個類是當監測到CPU有空閒時間的時候,將HTTP請求分發給handler類的router類springboot

package org.spring.springboot.router;

import org.spring.springboot.handler.CityHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;

@Configuration
public class CityRouter {

    @Bean
    public RouterFunction<ServerResponse> routeCity(CityHandler cityHandler) {
        return RouterFunctions.route(
                RequestPredicates.GET("/hello").and(RequestPredicates.accept(MediaType.TEXT_PLAIN)),
                cityHandler::helloCity);
    }

}

四、而後在最外層的主入口,Application.java併發

package org;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@SpringBootApplication
@ComponentScan("org.spring")
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

五、整個包的結構以下所示app

 

 六、而後程序跑起來啦

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::  (v2.0.6.BUILD-SNAPSHOT)

2019-03-05 07:37:15.713  INFO 8284 --- [           main] org.Application                          : Starting Application on DESKTOP-QGKILFJ with PID 8284 (D:\eclipse-workspace\webflux-test\target\classes started by weizhen in D:\eclipse-workspace\webflux-test)
2019-03-05 07:37:15.725  INFO 8284 --- [           main] org.Application                          : No active profile set, falling back to default profiles: default
2019-03-05 07:37:15.818  INFO 8284 --- [           main] onfigReactiveWebServerApplicationContext : Refreshing org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext@62e136d3: startup date [Tue Mar 05 07:37:15 CST 2019]; root of context hierarchy
2019-03-05 07:37:17.662  WARN 8284 --- [           main] reactor.ipc.netty.tcp.TcpResources       : [http] resources will use the default LoopResources: DefaultLoopResources {prefix=reactor-http, daemon=true, selectCount=4, workerCount=4}
2019-03-05 07:37:17.662  WARN 8284 --- [           main] reactor.ipc.netty.tcp.TcpResources       : [http] resources will use the default PoolResources: DefaultPoolResources {name=http, provider=reactor.ipc.netty.resources.PoolResources$$Lambda$188/243575009@2e554a3b}
2019-03-05 07:37:18.293  INFO 8284 --- [           main] o.s.w.r.f.s.s.RouterFunctionMapping      : Mapped ((GET && /hello) && Accept: [text/plain]) -> org.spring.springboot.router.CityRouter$$Lambda$197/416201381@64bc21ac
2019-03-05 07:37:18.310  INFO 8284 --- [           main] o.s.w.r.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.reactive.resource.ResourceWebHandler]
2019-03-05 07:37:18.310  INFO 8284 --- [           main] o.s.w.r.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.reactive.resource.ResourceWebHandler]
2019-03-05 07:37:18.437  INFO 8284 --- [           main] o.s.w.r.r.m.a.ControllerMethodResolver   : Looking for @ControllerAdvice: org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext@62e136d3: startup date [Tue Mar 05 07:37:15 CST 2019]; root of context hierarchy
2019-03-05 07:37:18.750  INFO 8284 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2019-03-05 07:37:20.073  INFO 8284 --- [ctor-http-nio-1] r.ipc.netty.tcp.BlockingNettyContext     : Started HttpServer on /0:0:0:0:0:0:0:0:8080
2019-03-05 07:37:20.074  INFO 8284 --- [           main] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port(s): 8080
2019-03-05 07:37:20.080  INFO 8284 --- [           main] org.Application                          : Started Application in 4.836 seconds (JVM running for 5.499)

七、進行訪問

這樣下來一個簡單的高併發框架就完成啦

可能有小夥伴看博主以前寫的博客都是關於機器學習的,還有salesforce的

其實吧,博主一直是作java的,兩年半以來作過GE的NPI CRM項目,惠普的Solr搜素項目,還有GE的語言助手項目,還有賽諾菲的供應鏈語音助手項目

爲何不寫java類的博客,主要是博客以爲java這個應該都算是基礎知識,應該是程序猿最基本的知識。

感受寫出來也不顯得吸引人眼球。因此沒寫。不過今天這個高併發確實很厲害。因此寫了一下

 

Thanks

WeiZhen

相關文章
相關標籤/搜索