springBoot发布https服务及调用

devtools/2024/12/27 1:03:07/

一、服务端发布https>https服务

1、准备SSL证书

(1)自签名证书:如果你只是用于开发或测试环境,可以生成一个自签名证书。
(2)CA 签名证书:对于生产环境,应该使用由受信任的证书颁发机构 (CA) 签名的证书。

这里采用生成自签名证书,可以使用keytool工具生成自签名证书(jdk工具):

keytool -genkeypair -alias myapp -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore keystore.p12 -validity 3650

这将创建一个有效期为 10 年的自签名证书,并将其存储在 keystore.p12 文件中。你需要提供一些信息,如组织名称等。注意记住密码和别名。

如下图:https>https://i-blog.csdnimg.cn/direct/8da97de68a1448969875ba3fac552ad0.png" width="1192" />

2、配置springboot启用HTTPS并指定SSL证书的位置和密码

application.propertiesapplication.yml都可以。这样配置可以读取环境变量

把证书放在resource的ssl目录下

server:port: 8443ssl:enabled: ${SSL_ENABLED:true}key-store: ${SSL_KEY_STORE:classpath:ssl/keystore.p12}key-store-password: ${SSL_KEY_STORE_PASSWORD:myapptest}keyStoreType: ${SSL_KEY_STORE_TYPE:PKCS12}keyAlias: ${SSL_KEY_ALIAS:myapp}

启动服务即可通过https>https访问了,默认可以设置成false

3、配置docker容器,启动https>https

把证书放在ssl目录下

version: "3"
services:test-https>https:image: openjdk:8-jdkcontainer_name: test-https>httpsrestart: alwaysports:- 22443:22443command: java -jar /opt/test-https>https.jarvolumes:- /home/services/test/:/opt/- /home/services/test/config/:/config/- /home/services/test/ssl/:/ssl/- /home/services/test/template_server/:/template_server/- /home/services/test/patch/:/patch/- /home/log/test/:/logs/environment:- TZ=Asia/Shanghai- SERVICE_HOST=${HOST_IP}- server.port=22443- NACOS_NAMESPACE=${NACOS_NAMESPACE}- NACOS_ADDR=${NACOS_ADDR}#开启https>https,如果不开启则配置为false- SSL_ENABLED=true#以下配置根据实际证书配置- SSL_KEY_STORE=ssl/keystore.p12- SSL_KEY_STORE_PASSWORD=myapptest- SSL_KEY_STORE_TYPE=PKCS12- SSL_KEY_ALIAS=myapp- JAVA_OPTS=-Xmx512m -XX:G1ConcRefinementThreads=4 -XX:MaxDirectMemorySize=1G

二、通过httpinvoke方法https>https服务

跳过证书校验

public class HttpInvokerRequestExecutorWithSession extends SimpleHttpInvokerRequestExecutor {private int connectTimeout=0;private int readTimeout=0;private SSLContext sslContext;private HostnameVerifier hostnameVerifier;private void initSsl() {try {sslContext = SSLContext.getInstance("TLS");sslContext.init(null, new TrustManager[]{new X509TrustManager() {public java.security.cert.X509Certificate[] getAcceptedIssuers() {return null;}public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {}public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {}}}, new SecureRandom());} catch (KeyManagementException | NoSuchAlgorithmException e) {logger.error("ssl init error:",e);throw new MsrRuntimeException(e.getMessage());}hostnameVerifier = (hostname, session) -> true;}/**** (non-Javadoc)** @see org.springframework.remoting.httpinvoker.SimpleHttpInvokerRequestExecutor*      #prepareConnection(java.net.HttpURLConnection, int)*/protected void prepareConnection(HttpURLConnection con, int contentLength) throws IOException {super.prepareConnection(con, contentLength);if (con instanceof HttpsURLConnection) {if (sslContext == null) {initSsl();}((HttpsURLConnection) con).setSSLSocketFactory(sslContext.getSocketFactory());((HttpsURLConnection) con).setHostnameVerifier(hostnameVerifier);}con.setConnectTimeout(connectTimeout);con.setReadTimeout(readTimeout);}/**** (non-Javadoc)** @see org.springframework.remoting.httpinvoker.SimpleHttpInvokerRequestExecutor*      #validateResponse(org.springframework.remoting.httpinvoker.HttpInvokerClientConfiguration,*      java.net.HttpURLConnection)*/protected void validateResponse(HttpInvokerClientConfiguration config, HttpURLConnection con)throws IOException {super.validateResponse(config, con);}public int getConnectTimeout() {return connectTimeout;}public void setConnectTimeout(int connectTimeout) {this.connectTimeout = connectTimeout;}public int getReadTimeout() {return readTimeout;}public void setReadTimeout(int readTimeout) {this.readTimeout = readTimeout;}}

三、feign接口调用https>https服务

跳过证书校验。feign接口的地址还是正常配置httphttps>https都支持

import feign.Client;
import feign.Contract;
import feign.RequestInterceptor;
import feign.codec.ErrorDecoder;
import feign.jaxrs.JAXRSContract;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;@Configuration
public class FeignConfiguration {@Autowiredprivate BusinessConfig businessConfig;/*** yaml中的配置未生效,暂时在配置类中配置*/@Beanpublic Contract getFeignContract() {return new JAXRSContract();}@Beanpublic ErrorDecoder getFeignErrorDecoder() {return new FeignExceptionDecoder();}@Beanpublic OkHttpClient okHttpClient() {if(businessConfig.getRootServiceUrl() != null && businessConfig.getRootServiceUrl().contains("https>https")){try {TrustManager[] trustManagers = getTrustManager();if (trustManagers == null || trustManagers.length == 0) {throw new IllegalStateException("Failed to create trust managers");}SSLSocketFactory sslSocketFactory = getSSLSocketFactory();if (sslSocketFactory == null) {throw new IllegalStateException("Failed to initialize SSL socket factory");}return new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).connectTimeout(60, TimeUnit.SECONDS).writeTimeout(120, TimeUnit.SECONDS).connectionPool(new ConnectionPool()).sslSocketFactory(sslSocketFactory, (X509TrustManager) trustManagers[0]).hostnameVerifier((hostname, session) -> true).build();} catch (Exception e) {throw new RuntimeException("Failed to create OkHttpClient", e);}}return new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).connectTimeout(60, TimeUnit.SECONDS).writeTimeout(120, TimeUnit.SECONDS).connectionPool(new ConnectionPool()).build();}@Beanpublic RequestInterceptor requestInterceptor() {return new CustomRequestInterceptor(businessConfig);}@Beanpublic Client feignClient(OkHttpClient okHttpClient) {return new CustomClient(new feign.okhttp.OkHttpClient(okHttpClient));}private TrustManager[] getTrustManager() {try {TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {public X509Certificate[] getAcceptedIssuers() {return new X509Certificate[0];}public void checkClientTrusted(X509Certificate[] certs, String authType) {}public void checkServerTrusted(X509Certificate[] certs, String authType) {}}};return trustAllCerts;} catch (Exception e) {throw new RuntimeException(e);}}private SSLSocketFactory getSSLSocketFactory() {try {SSLContext sc = SSLContext.getInstance("TLS");sc.init(null, getTrustManager(), new SecureRandom());return sc.getSocketFactory();} catch (Exception e) {throw new RuntimeException(e);}}}


http://www.ppmy.cn/devtools/145669.html

相关文章

【微信小程序】微信小程序中的异步函数是如何实现同步功能的

在微信小程序中,虽然很多 API 都是异步的,但可以通过一些方法来实现类似同步的功能。以下是几种常见的方法: 1. 使用 async/await async/await 是 ES2017 引入的语法糖,它基于 Promise 来实现异步操作的同步化写法。 示例代码 …

基于谱聚类的多模态多目标浣熊优化算法(MMOCOA-SC)求解ZDT1-ZDT4,ZDT6和工程应用--盘式制动器优化,MATLAB代码

一、MMOCOA-SC介绍 基于谱聚类的多模态多目标浣熊优化算法(Multimodal Multi-Objective Coati Optimization Algorithm Based on Spectral Clustering,MMOCOA-SC)是2024年提出的一种多模态多目标优化算法,该算法的核心在于使用谱…

FFmpeg音频解码详解

FFmpeg 探索之旅 一、FFmpeg 简介与环境搭建 二、FFmpeg 主要结构体剖析 三、FFmpeg 视频解码详解 FFmpeg音频解码详解 FFmpeg 探索之旅前言一、音频编码与解码基础(一)音频编码简述(二)音频解码本质 二、音频解码关键 API 深度剖…

TCP/IP 邮件

TCP/IP邮件是互联网通信中非常重要的应用之一。当我们发送电子邮件时,我们实际上并没有直接使用TCP/IP协议,而是通过电子邮件程序,例如微软的Outlook、莲花软件的Notes或Netscape Communicator等来实现。这些电子邮件程序背后使用了不同的TCP…

Redis 集群架构:高可用与扩展性

一、引言 在当今数字化时代,数据量呈爆炸式增长,对数据存储和处理的要求也越来越高。Redis作为一款高性能的键值对存储数据库,其集群架构在应对高并发、大数据量场景时展现出了独特的优势,成为众多企业构建高效、稳定系统的关键技…

20241225在ubuntu20.04.5下监控SSD

20241225在ubuntu20.04.5下监控SSD 2024/12/25 20:29 参考资料: 百度:ubuntu查看ssd寿命 方法 1:使用「磁盘」工具监测 SSD 健康状态 sudo apt install gnome-disk-utility 方法 2:使用 smartctl 工具检查 SSD 健康状态 Ubuntu 和…

Diffusers使用笔记

Diffusers 是用于生成图像、音频等最先进预训练扩散模型的库。它既支持推理解决方案,也支持训练自己的扩散模型,Diffusers 是一个支持这两者的模块化工具箱。区别与ComfyUI与webUI这类UI类的应用,Diffusers实际上是更底层的库,可以…

字节跳动C++面试题及参考答案(下)

说说B 树 b + 树 B 树: B 树是一种平衡的多路查找树,它的设计目的是为了减少磁盘 I/O 操作,适用于存储大量的数据并进行高效的查找、插入和删除操作。B 树的节点可以有多个子节点(通常称为多路),每个节点包含多个关键字,关键字之间是有序的。 B 树的结构特点包括:根节点…