Springboot-WebFlux實現http重定向到https

1 簡介

Spring WebFlux是一個新興的技術,Spring團隊把寶都壓在響應式Reactive上了,因而推出了全新的Web實現。本文不討論響應式編程,而是經過實例講解Springboot WebFlux如何把http重定向到httpsjava

spring mvc and webflux venn

做爲餐前小吃,建議你們先吃如下https小菜,以幫助理解:react

(1)Springboot整合https原來這麼簡單nginx

(2)HTTPS之密鑰知識與密鑰工具Keytool和Keystore-Explorerweb

(3)Springboot以Tomcat爲容器實現http重定向到https的兩種方式spring

(4)Springboot以Jetty爲容器實現http重定向到https編程

(5)nginx開啓ssl並把http重定向到https的兩種方式tomcat

2 搭建WebFlux項目

引入WebFlux的依賴以下:springboot

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

實現Controller,與以前略有不一樣,返回值爲Mono<T>微信

@RestController
public class HelloController {
    @GetMapping("/hello")
    public Mono<String> hello() {
        return Mono.just("Welcome to www.pkslow.com");
    }
}

配置文件與普通的Springboot項目沒什麼差異,配置了兩個端口,並配置SSL相關參數:mvc

server.port=443
http.port=80

server.ssl.enabled=true
server.ssl.key-store-type=jks
server.ssl.key-store=classpath:localhost.jks
server.ssl.key-store-password=changeit
server.ssl.key-alias=localhost

3 重定向實現

主要作了兩件事:

(1)在有https的狀況下,啓動另外一個http服務,主要經過NettyReactiveWebServerFactory來生成一個Web服務。

(2)把http重定向到https,這裏作了路徑判斷,加了一個簡單的過濾函數。經過提供一個新的HttpHandler來實現重定向。

package com.pkslow.ssl.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.HttpHandler;
import reactor.core.publisher.Mono;
import javax.annotation.PostConstruct;
import java.net.URI;
import java.net.URISyntaxException;

@Configuration
public class HttpToHttpsConfig {

    @Value("${server.port}")
    private int httpsPort;

    @Value("${http.port}")
    private int httpPort;


    @Autowired
    private HttpHandler httpHandler;

    @PostConstruct
    public void startRedirectServer() {
        NettyReactiveWebServerFactory factory = new NettyReactiveWebServerFactory(httpPort);
        factory.getWebServer(
                (request, response) -> {
                    URI uri = request.getURI();
                    URI httpsUri;
                    try {
                        if (isNeedRedirect(uri.getPath())) {
                            httpsUri = new URI("https",
                                    uri.getUserInfo(),
                                    uri.getHost(),
                                    httpsPort,
                                    uri.getPath(),
                                    uri.getQuery(),
                                    uri.getFragment());
                            response.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
                            response.getHeaders().setLocation(httpsUri);
                            return response.setComplete();
                        } else {
                            return httpHandler.handle(request, response);
                        }

                    } catch (URISyntaxException e) {
                        return Mono.error(e);
                    }
                }
        ).start();

    }

    private boolean isNeedRedirect(String path) {
        return !path.startsWith("/actuator");
    }
}

4 總結

本文詳細代碼可在南瓜慢說公衆號回覆<SpringbootSSLRedirectWebFlux>獲取。


歡迎訪問南瓜慢說 www.pkslow.com獲取更多精彩文章!

歡迎關注微信公衆號<南瓜慢說>,將持續爲你更新...

多讀書,多分享;多寫做,多整理。

相關文章
相關標籤/搜索