ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

SpringBoot 集成 RustFS

SpringBoot 集成 RustFS SpringBoot 集成 RustFS1 配置1.1 Docker容器1.2 Spring配置2 依赖3 代码3.1 FileController3.2 RustFsConfig3.3 RustFsProperties3.4 RustFsStorageService1 配置1.1 Docker容器services:rustfs:image:rustfs/rustfs:latestcontainer_name:rustfsrestart:unless-stoppedsecurity_opt:-no-new-privileges:truenetworks:-hyacinthports:-9500:9000# S3 API避开 MinIO 的 9000-9501:9001# RustFS 控制台environment:# 本机单磁盘开发模式避免把同一物理磁盘伪装成四块独立磁盘。RUSTFS_VOLUMES:/dataRUSTFS_ADDRESS:0.0.0.0:9000RUSTFS_CONSOLE_ADDRESS:0.0.0.0:9001RUSTFS_CONSOLE_ENABLE:trueRUSTFS_CONSOLE_CORS_ALLOWED_ORIGINS:*RUSTFS_ACCESS_KEY:rustfsadminRUSTFS_SECRET_KEY:rustfsadminRUSTFS_OBS_LOGGER_LEVEL:infoRUSTFS_OBS_LOG_DIRECTORY:/app/logsvolumes:-D:/Env/docker/rustfs/data:/data-D:/Env/docker/rustfs/logs:/app/logs1.2 Spring配置spring:application:name:spring-fileservlet:multipart:max-file-size:100MBmax-request-size:100MBrustfs:endpoint:${RUSTFS_ENDPOINT:http://localhost:9500}access-key:${RUSTFS_ACCESS_KEY:rustfsadmin}secret-key:${RUSTFS_SECRET_KEY:rustfsadmin}region:${RUSTFS_REGION:us-east-1}bucket:${RUSTFS_BUCKET:spring-file}2 依赖?xml version1.0 encodingUTF-8?projectxmlnshttp://maven.apache.org/POM/4.0.0xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsdmodelVersion4.0.0/modelVersionparentgroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-parent/artifactIdversion4.1.1/versionrelativePath//parentgroupIdcom.xu/groupIdartifactIdspring-file/artifactIdversion1.0.0/versionpropertiesjava.version25/java.version/propertiesdependencyManagementdependenciesdependencygroupIdsoftware.amazon.awssdk/groupIdartifactIdbom/artifactIdversion2.55.6/versiontypepom/typescopeimport/scope/dependency/dependencies/dependencyManagementdependenciesdependencygroupIdsoftware.amazon.awssdk/groupIdartifactIds3/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-webmvc/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-devtools/artifactIdscoperuntime/scopeoptionaltrue/optional/dependencydependencygroupIdorg.projectlombok/groupIdartifactIdlombok/artifactIdoptionaltrue/optional/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-webmvc-test/artifactIdscopetest/scope/dependency/dependenciesbuildpluginsplugingroupIdorg.graalvm.buildtools/groupIdartifactIdnative-maven-plugin/artifactId/pluginplugingroupIdorg.springframework.boot/groupIdartifactIdspring-boot-maven-plugin/artifactId/pluginplugingroupIdorg.apache.maven.plugins/groupIdartifactIdmaven-compiler-plugin/artifactIdexecutionsexecutioniddefault-compile/idphasecompile/phasegoalsgoalcompile/goal/goalsconfigurationannotationProcessorPathspathgroupIdorg.projectlombok/groupIdartifactIdlombok/artifactId/path/annotationProcessorPaths/configuration/executionexecutioniddefault-testCompile/idphasetest-compile/phasegoalsgoaltestCompile/goal/goalsconfigurationannotationProcessorPathspathgroupIdorg.projectlombok/groupIdartifactIdlombok/artifactId/path/annotationProcessorPaths/configuration/execution/executions/plugin/plugins/build/project3 代码3.1 FileControllerpackagecom.xu.spring.file.rustfs;importjava.io.IOException;importjava.util.Map;importorg.springframework.http.MediaType;importorg.springframework.web.bind.annotation.DeleteMapping;importorg.springframework.web.bind.annotation.PathVariable;importorg.springframework.web.bind.annotation.PostMapping;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.RestController;importorg.springframework.web.multipart.MultipartFile;RestControllerRequestMapping(/api/files)publicclassFileController{privatefinalRustFsStorageServicestorageService;publicFileController(RustFsStorageServicestorageService){this.storageServicestorageService;}PostMapping(consumes{MediaType.MULTIPART_FORM_DATA_VALUE,MediaType.MULTIPART_MIXED_VALUE})publicMapString,Stringupload(RequestParam(file)MultipartFilefile)throwsIOException{StringobjectKeystorageService.upload(file);returnMap.of(message,上传成功,key,objectKey);}DeleteMapping(/{key})publicMapString,Stringdelete(PathVariableStringkey){storageService.delete(key);returnMap.of(message,删除成功);}}3.2 RustFsConfigpackagecom.xu.spring.file.rustfs;importjava.net.URI;importorg.springframework.boot.context.properties.EnableConfigurationProperties;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importsoftware.amazon.awssdk.auth.credentials.AwsBasicCredentials;importsoftware.amazon.awssdk.auth.credentials.StaticCredentialsProvider;importsoftware.amazon.awssdk.regions.Region;importsoftware.amazon.awssdk.services.s3.S3Client;ConfigurationEnableConfigurationProperties(RustFsProperties.class)publicclassRustFsConfig{BeanpublicS3ClientrustFsS3Client(RustFsPropertiesproperties){AwsBasicCredentialscredentialsAwsBasicCredentials.create(properties.accessKey(),properties.secretKey());returnS3Client.builder().endpointOverride(URI.create(properties.endpoint())).region(Region.of(properties.region())).credentialsProvider(StaticCredentialsProvider.create(credentials)).forcePathStyle(true).build();}}3.3 RustFsPropertiespackagecom.xu.spring.file.rustfs;importorg.springframework.boot.context.properties.ConfigurationProperties;ConfigurationProperties(prefixrustfs)publicrecordRustFsProperties(Stringendpoint,StringaccessKey,StringsecretKey,Stringregion,Stringbucket){}3.4 RustFsStorageServicepackagecom.xu.spring.file.rustfs;importjava.io.IOException;importjava.io.InputStream;importjava.util.UUID;importorg.springframework.stereotype.Service;importorg.springframework.util.StringUtils;importorg.springframework.web.multipart.MultipartFile;importsoftware.amazon.awssdk.core.sync.RequestBody;importsoftware.amazon.awssdk.services.s3.S3Client;importsoftware.amazon.awssdk.services.s3.model.DeleteObjectRequest;importsoftware.amazon.awssdk.services.s3.model.PutObjectRequest;ServicepublicclassRustFsStorageService{privatefinalS3Clients3Client;privatefinalRustFsPropertiesproperties;publicRustFsStorageService(S3Clients3Client,RustFsPropertiesproperties){this.s3Clients3Client;this.propertiesproperties;}publicStringupload(MultipartFilefile)throwsIOException{if(file.isEmpty()){thrownewIllegalArgumentException(上传文件不能为空);}Stringsuffix;StringoriginalFilenamefile.getOriginalFilename();if(StringUtils.hasText(originalFilename)){intindexoriginalFilename.lastIndexOf(.);if(index0){suffixoriginalFilename.substring(index);}}StringobjectKeyUUID.randomUUID()suffix;PutObjectRequestrequestPutObjectRequest.builder().bucket(properties.bucket()).key(objectKey).contentType(StringUtils.hasText(file.getContentType())?file.getContentType():application/octet-stream).build();try(InputStreaminputStreamfile.getInputStream()){s3Client.putObject(request,RequestBody.fromInputStream(inputStream,file.getSize()));}returnobjectKey;}publicvoiddelete(StringobjectKey){DeleteObjectRequestrequestDeleteObjectRequest.builder().bucket(properties.bucket()).key(objectKey).build();s3Client.deleteObject(request);}}
返回列表