首页 > 其他分享 >应用同时支持HTTP和HTTPS

应用同时支持HTTP和HTTPS

时间:2024-06-21 14:53:33浏览次数:9  
标签:HTTP HTTPS springframework server httpPort 应用 org import port

生成证书:keytool -genkeypair -keystore test.jks -alias test -keyalg RSA -keysize 2048 -validity 3650
应用配置:
server: port: 18081 #https http-port: 8081 #http ssl: key-store: /test.jks # 密钥库路径 key-store-password: ENC(djVg6Ri/rp7cHwh9ZTmq/Q==) # 密钥库密码 key-alias: test # 密钥库别名 enabled: true

网关服务(NettyServer):

import cn.hutool.extra.spring.SpringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory;
import org.springframework.boot.web.server.WebServer;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Objects;

@Slf4j
@Component
@RequiredArgsConstructor
@ConditionalOnProperty(value = "server.ssl.enabled", havingValue = "true")
public class NettyServerCustomer {
    private final HttpHandler httpHandler;

    @PostConstruct
    public void start() {
        Integer httpPort = SpringUtil.getProperty("server.http-port", Integer.class, null);
        if (Objects.nonNull(httpPort)) {
            NettyReactiveWebServerFactory factory = new NettyReactiveWebServerFactory(httpPort);
            WebServer webServer = factory.getWebServer(httpHandler);
            webServer.start();
            log.info("Netty Server Started, HTTP Port: {}", httpPort);
        }
    }
}

业务服务(Tomcat、Undertow):

import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.Connector;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
@ConditionalOnProperty(value = "server.ssl.enabled", havingValue = "true")
public class TomcatServerCustomer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {
    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        Integer httpPort = SpringUtil.getProperty("server.http-port", Integer.class, null);
        if (Objects.nonNull(httpPort)) {
            Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
            connector.setPort(httpPort);
            connector.setScheme("http");
            factory.addAdditionalTomcatConnectors(connector);
            log.info("Tomcat Server Started, HTTP Port: {}", httpPort);
        }
    }
}




import cn.hutool.extra.spring.SpringUtil;
import io.undertow.UndertowOptions;
import io.undertow.servlet.api.SecurityConstraint;
import io.undertow.servlet.api.SecurityInfo;
import io.undertow.servlet.api.TransportGuaranteeType;
import io.undertow.servlet.api.WebResourceCollection;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
@ConditionalOnProperty(value = "server.ssl.enabled", havingValue = "true")
public class UndertowServerCustomer implements WebServerFactoryCustomizer<UndertowServletWebServerFactory> {
@Override
public void customize(UndertowServletWebServerFactory factory) {
Integer httpPort = SpringUtil.getProperty("server.http-port", Integer.class, null);
Integer httpsPort = SpringUtil.getProperty("server.port", Integer.class, null);
if (Objects.nonNull(httpPort) && Objects.nonNull(httpsPort)) {
factory.addBuilderCustomizers(builder -> {
builder.addHttpListener(httpPort, "0.0.0.0");
builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true);
});
factory.addDeploymentInfoCustomizers(deploymentInfo ->
deploymentInfo.addSecurityConstraint(
new SecurityConstraint()
.addWebResourceCollection(new WebResourceCollection().addUrlPatterns("/*"))
.setTransportGuaranteeType(TransportGuaranteeType.CONFIDENTIAL)
.setEmptyRoleSemantic(SecurityInfo.EmptyRoleSemantic.PERMIT))
.setConfidentialPortManager(e -> httpsPort));
log.info("Undertow Server Started, HTTP Port: {}", httpPort);
}
}
}

此时应用启动后,支持http与https;

注册中心注册的端口时https,若以http为主,则还需修改 FeignClient、RestTemplate配置以支持https;

若要以http为主,则修改注册中心注册端口

spring:
  cloud:
    consul:
      discovery:
        port: ${server.http-port:${server.port}}
    nacos:
      discovery:
        port: ${server.http-port:${server.port}}

若不想启停https时来回修改端口

import cn.hutool.core.util.BooleanUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;

import java.util.Properties;
/**
* 将该类加入spring.factories
* org.springframework.boot.env.EnvironmentPostProcessor=com.leadingtek.arteryf.gateway.config.ServerPortEnvPostProcessor
*
*/

public class ServerPortEnvPostProcessor implements EnvironmentPostProcessor, Ordered {
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        String sslPortEnable = environment.getProperty("server.ssl.enabled");
        Integer httpPort = environment.getProperty("server.http-port", Integer.class);
        if (!BooleanUtil.toBoolean(sslPortEnable) && httpPort != null) {
            Properties properties = new Properties();
            properties.put("server.port", httpPort);
            MutablePropertySources propertySources = environment.getPropertySources();
            propertySources.addFirst(new PropertiesPropertySource("server-port-properties", properties));
        }
    }

    @Override
    public int getOrder() {
        return Integer.MAX_VALUE;
    }
}

 

标签:HTTP,HTTPS,springframework,server,httpPort,应用,org,import,port
From: https://www.cnblogs.com/langty/p/18260520

相关文章

  • 振弦采集仪在桥梁工程中的应用与发展趋势
    振弦采集仪在桥梁工程中的应用与发展趋势振弦采集仪作为一种精密的传感器测量设备,在桥梁工程中扮演着至关重要的角色,它通过监测桥梁结构的振动频率和弦张力变化来评估结构的健康状况和承载能力。随着桥梁工程技术的不断进步和智能化趋势的发展,振弦采集仪的应用日益广泛,其在桥梁工......
  • RSA密码系统的特定密钥泄露攻击与Coppersmith方法的应用
    PrimiHub一款由密码学专家团队打造的开源隐私计算平台,专注于分享数据安全、密码学、联邦学习、同态加密等隐私计算领域的技术和内容。RSA密码系统作为当前最广泛使用的公钥加密算法之一,其安全性依赖于大整数分解问题的困难性。然而,随着计算能力的提高和算法优化,特别是Coppersmi......
  • IIS应用程序回收导致应用中Hangfire等后台任务无法正常启动工作的解决方法
    一些解释这个锅的确是IIS的,我不冤枉它:1)应用程序池在回收时,将删除正在运行的工作进程,然后再次启动它。2)正如定义所指出的,如果您设置“AlwaysRunning”,则在IIS启动或创建应用程序池时,立即启动应用程序池的工作进程。OnDemand->IIS将在接收到Web应用程序的第一个请求时启动工......
  • 【TensorFlow深度学习】量化压缩技术在降低模型体积中的应用
    量化压缩技术在降低模型体积中的应用量化压缩技术在降低模型体积中的应用1.引言2.量化压缩基础3.实战:使用TensorFlowLite进行模型量化4.评估量化效果5.结果分析与优化建议6.结语量化压缩技术在降低模型体积中的应用在深度学习领域,模型的......
  • 用ADAU1466开发板教你做音频开发,有手就行(二十二):按键控制音量+-和静音(IO的应用)
    作者的话本章开始正式进入ADAU1466的开发教程,什么叫有手就行,看下去就明白了。特别注意因为ADAU1452和ADAU1466是P2P完全兼容的,管脚兼容,硬件设计兼容,软件程序配置全部都兼容,差别在于ADAU1466的内存更大。我的文章里所用到的程序都是基于ADAU1452的,程序也是基于ADAU1452的,A......
  • 北斗短报文终端在应急消防通信场景中的应用
    在应对自然灾害和紧急情况时,北斗三号短报文终端以其全球覆盖、实时通信和精准定位的能力,成为应急消防通信的得力助手。它不仅能够在地面通信中断的极端条件下保障信息传递的畅通,还能提供精准的位置信息,为救援行动提供有力支持。北斗三号短报文终端在应急消防通信场景中的应用......
  • Windows的Gitlab Runner搭配的PowerShell脚本:发布传统ASP.NET Web应用程序
    简介GitlabRunner在Windows上运行之后,我们在.gitlab-ci.yml中编写script语句,思路和Linux是一样。但是考虑到Windows的特点,为了让程序员少接触一些知识点,以及给未来执行作业的时候预留更多的操作空间。简单说就是未来修改执行作业时候的逻辑,但是每个软件仓库根目录下的.gitlab-ci......
  • kettle从入门到精通 第七十二课 ETL之kettle 三谈http post(含文件上传),彻底掌握参数传
    场景:群里有个小伙伴在使用httppost步骤调用接口时遇到问题,postman调用正常,但是kettle中调用异常。 解决方案:既然postman调用接口正常,肯定是httppost步骤中某些参数设置的不正确导致的。那就把常用的方式都梳理下,搞定它。 1、httppost请求参数放到body中,Content-Type是appl......
  • cv2在图像上的应用-续2
    接上篇,255值剃平头法原文称为线性变换,只能说是区间线性,其第二个“直方图正规化”方法称为全线性是合适的,只是“直方”是见不着的,其原理是假设图片的灰度值是n-m之间,而8位灰度值的最大区间是0-255,就按比列把像素灰度值略膨胀到较大的区间即可,值就不会大于255,计算公式是像素q=(255-0......
  • java httpsession
    bychatgpt=>HttpSessionHttpSession是JavaServletAPI提供的一个接口,用于管理与单个用户相关的会话信息。会话(session)是在服务器端保存的与客户端用户交互的一系列请求和响应之间的状态信息。以下是HttpSession的详细解释:HttpSession的作用HttpSession用于在用户的多......