liusuyi
2025-12-23 7b062016854168116094f780228a3e2f163d98b8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
package com.ard.oss.service.impl;
 
import com.ard.common.config.OssConfiguration;
import com.ard.oss.model.CredentialsDTO;
import com.ard.oss.model.enums.OssTypeEnum;
import com.ard.oss.service.IOssService;
import io.minio.*;
import io.minio.credentials.AssumeRoleProvider;
import io.minio.errors.*;
import io.minio.http.Method;
import lombok.extern.slf4j.Slf4j;
import okhttp3.ConnectionPool;
import okhttp3.ConnectionSpec;
import okhttp3.OkHttpClient;
import okhttp3.TlsVersion;
import org.springframework.stereotype.Service;
 
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.ProviderException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
 
import static com.ard.common.config.OssConfiguration.*;
 
/**
 * @author sean
 * @version 0.3
 * @date 2021/12/23
 */
@Service
@Slf4j
public class MinIOServiceImpl implements IOssService {
 
    private MinioClient client;
 
    @Override
    public String getOssType() {
        return OssTypeEnum.MINIO.getType();
    }
 
 
    public CredentialsDTO getCredentials111() {
        try {
            AssumeRoleProvider provider = new AssumeRoleProvider(endpoint, accessKey,
                    secretKey, Math.toIntExact(OssConfiguration.expire),
                    null, OssConfiguration.region, null, null, null, null);
            return new CredentialsDTO(provider.fetch(), OssConfiguration.expire);
        } catch (NoSuchAlgorithmException e) {
            log.debug("Failed to obtain sts.");
            e.printStackTrace();
        }
        return null;
    }
    @Override
    public CredentialsDTO getCredentials() {
        try {
            // 创建自签证书的 OkHttpClient
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] chain, String authType) {}
                        @Override
                        public void checkServerTrusted(X509Certificate[] chain, String authType) {}
                        @Override
                        public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[]{}; }
                    }
            };
            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
            sslContext.init(null, trustAllCerts, new SecureRandom());
 
            ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                    .tlsVersions(TlsVersion.TLS_1_2)
                    .allEnabledCipherSuites()
                    .build();
 
            OkHttpClient httpClient = new OkHttpClient.Builder()
                    .sslSocketFactory(sslContext.getSocketFactory(),
                            (X509TrustManager) trustAllCerts[0])
                    .hostnameVerifier((hostname, session) -> true)
                    .connectionSpecs(Collections.singletonList(spec)) // ⭐关键
                    .connectionPool(new ConnectionPool(0, 1, TimeUnit.SECONDS)) // ⭐禁用复用
                    .build();
 
            // 构建 AssumeRoleProvider,使用自定义 httpClient
            AssumeRoleProvider provider = new AssumeRoleProvider(
                    endpoint,
                    accessKey,
                    secretKey,
                    Math.toIntExact(OssConfiguration.expire),
                    null,
                    OssConfiguration.region,
                    null,
                    null,
                    null,
                    httpClient
            );
 
            // 获取 STS 凭证
            var stsCredentials = provider.fetch();
            return new CredentialsDTO(stsCredentials, OssConfiguration.expire);
 
        } catch (ProviderException e) {
            log.error("Failed to parse STS response", e);
            throw new RuntimeException("STS response parse failed", e);
        } catch (NoSuchAlgorithmException | java.security.KeyManagementException e) {
            log.error("Failed to create custom SSL context", e);
            throw new RuntimeException("SSL setup failed", e);
        }
    }
 
    @Override
    public URL getObjectUrl(String bucket, String objectKey) {
        try {
            return new URL(
                    client.getPresignedObjectUrl(
                            GetPresignedObjectUrlArgs.builder()
                                    .method(Method.GET)
                                    .bucket(bucket)
                                    .object(objectKey)
                                    .expiry(Math.toIntExact(OssConfiguration.expire))
                                    .build()));
        } catch (ErrorResponseException | InsufficientDataException | InternalException |
                 InvalidKeyException | InvalidResponseException | IOException |
                 NoSuchAlgorithmException | XmlParserException | ServerException e) {
            throw new RuntimeException("The file does not exist on the OssConfiguration.");
        }
    }
 
    @Override
    public Boolean deleteObject(String bucket, String objectKey) {
        try {
            client.removeObject(RemoveObjectArgs.builder()
                    .bucket(bucket)
                    .object(objectKey)
                    .build());
        } catch (MinioException | NoSuchAlgorithmException | IOException | InvalidKeyException e) {
            log.error("Failed to delete file.");
            e.printStackTrace();
            return false;
        }
        return true;
    }
 
    @Override
    public InputStream getObject(String bucket, String objectKey) {
        try {
            GetObjectResponse object = client.getObject(GetObjectArgs.builder()
                    .bucket(bucket)
                    .object(objectKey)
                    .build());
            return new ByteArrayInputStream(object.readAllBytes());
        } catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidKeyException | InvalidResponseException | IOException | NoSuchAlgorithmException | ServerException | XmlParserException e) {
            e.printStackTrace();
        }
        return InputStream.nullInputStream();
    }
 
    @Override
    public void putObject(String bucket, String objectKey, InputStream input) {
        try {
            client.statObject(StatObjectArgs.builder()
                    .bucket(bucket)
                    .object(objectKey)
                    .build());
            throw new RuntimeException("The filename already exists.");
        } catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
            log.info("The file does not exist, start uploading.");
            try {
                // 设置 partSize 为 10MB
                long partSize = 10 * 1024 * 1024;
                ObjectWriteResponse response = client.putObject(
                        PutObjectArgs.builder()
                                .bucket(bucket)
                                .object(objectKey)
                                .stream(input, -1, partSize)
                                .build());
                log.info("Upload File: {}", response.etag());
            } catch (MinioException | IOException | InvalidKeyException | NoSuchAlgorithmException ex) {
                log.error("Failed to upload File {}.", objectKey);
                ex.printStackTrace();
            }
        }
    }
 
    @Override
    public void putObject(String bucket, String objectKey, InputStream input, String contentType) {
        try {
            // 检查文件是否已经存在
            client.statObject(StatObjectArgs.builder()
                    .bucket(bucket)
                    .object(objectKey)
                    .build());
            throw new RuntimeException("The file already exists: " + objectKey);
        } catch (ErrorResponseException e) {
            // 如果文件不存在,则继续上传
            log.info("The file does not exist, start uploading.");
            try {
                // 设置 partSize 为 10MB
                long partSize = 10 * 1024 * 1024; // 每块 10MB
                PutObjectArgs.Builder putArgsBuilder = PutObjectArgs.builder()
                        .bucket(bucket)
                        .object(objectKey)
                        .stream(input, -1, partSize);
 
                // 如果提供了 Content-Type,则设置该类型
                if (contentType != null && !contentType.isEmpty()) {
                    putArgsBuilder.contentType(contentType);
                }
 
                // 上传文件
                ObjectWriteResponse response = client.putObject(putArgsBuilder.build());
                log.info("Uploaded file successfully: {}, ETag: {}", objectKey, response.etag());
 
            } catch (MinioException | IOException | InvalidKeyException | NoSuchAlgorithmException ex) {
                log.error("Failed to upload file: {}", objectKey, ex);
                throw new RuntimeException("File upload failed: " + objectKey, ex);
            }
        } catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
            // 如果 statObject 发生错误,说明服务端错误或其他问题
            log.error("Failed to check if file exists: {}", objectKey, e);
            throw new RuntimeException("Failed to check if file exists: " + objectKey, e);
        }
    }
 
    @Override
    public void createClient() {
        if (Objects.nonNull(this.client)) {
            return;
        }
        try {
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] chain, String authType) {}
                        @Override
                        public void checkServerTrusted(X509Certificate[] chain, String authType) {}
                        @Override
                        public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[]{}; }
                    }
            };
 
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, new SecureRandom());
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
 
            OkHttpClient httpClient = new OkHttpClient.Builder()
                    .sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0])
                    .hostnameVerifier((hostname, session) -> true)
                    .connectionSpecs(Collections.singletonList(
                            new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                                    .tlsVersions(TlsVersion.TLS_1_2)   // 强制 TLS1.2
                                    .build()
                    ))
                    .build();
 
            this.client = MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey)
                    .httpClient(httpClient)
                    .build();
        } catch (Exception e) {
            throw new RuntimeException("Failed to create unsafe MinioClient", e);
        }
    }
}